"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
    return typeof obj
} : function (obj) {
    return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj
};

function _toConsumableArray(arr) {
    if (Array.isArray(arr)) {
        for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) {
            arr2[i] = arr[i]
        }
        return arr2
    } else {
        return Array.from(arr)
    }
}
function getAliId() {
    var t = window.location,
        e = "";
    e = /[\?|&]ali=(\d+)/.exec(t)[1];
    return e;
}
var x5Url = window.location.href;
console.log('testAl', x5Url)
if (x5Url.indexOf('_____tmd_____') != -1) {
    if (x5Url.indexOf('nc_app_key') === -1) {
        localStorage.setItem('ali', getAliId())
        console.log('ali', getAliId())
        chrome.runtime.sendMessage({
            type: "removeCookie",
            url: "http://pub.alimama.com/",
            name: 'x5sec'
        },
            (function (t) {
                console.log(t)
            }))
    } else {
        chrome.runtime.sendMessage({
            type: "cookie",
            url: "https://pub.alimama.com/",
            name: "x5sec"
        },
            (function (e) {
                console.log(e)
                if (e) {
                    var x5url = 'https://zsxt.letuilm.com/api/activity/setX5sec?x5sec=' + e + "&ali=" + localStorage.getItem('ali');
                    console.log(x5url)
                    $['ajax']({
                        url: x5url,
                        type: 'get',
                        success: function (e) {
                            window.close();
                        }
                    })
                }
            }))
    }
}
// console.log('222')
var CryptoJS = CryptoJS || function (u, p) {
    var d = {},
        l = d.lib = {},
        s = function s() { },
        t = l.Base = {
            extend: function extend(a) {
                s.prototype = this;
                var c = new s();
                a && c.mixIn(a);
                c.hasOwnProperty("init") || (c.init = function () {
                    c.$super.init.apply(this, arguments)
                });
                c.init.prototype = c;
                c.$super = this;
                return c
            },
            create: function create() {
                var a = this.extend();
                a.init.apply(a, arguments);
                return a
            },
            init: function init() { },
            mixIn: function mixIn(a) {
                for (var c in a) {
                    a.hasOwnProperty(c) && (this[c] = a[c])
                }
                a.hasOwnProperty("toString") && (this.toString = a.toString)
            },
            clone: function clone() {
                return this.init.prototype.extend(this)
            }
        },
        r = l.WordArray = t.extend({
            init: function init(a, c) {
                a = this.words = a || [];
                this.sigBytes = c != p ? c : 4 * a.length
            },
            toString: function toString(a) {
                return (a || v).stringify(this)
            },
            concat: function concat(a) {
                var c = this.words,
                    e = a.words,
                    j = this.sigBytes;
                a = a.sigBytes;
                this.clamp();
                if (j % 4)
                    for (var k = 0; k < a; k++) {
                        c[j + k >>> 2] |= (e[k >>> 2] >>> 24 - 8 * (k % 4) & 255) << 24 - 8 * ((j + k) % 4)
                    } else if (65535 < e.length)
                    for (k = 0; k < a; k += 4) {
                        c[j + k >>> 2] = e[k >>> 2]
                    } else c.push.apply(c, e);
                this.sigBytes += a;
                return this
            },
            clamp: function clamp() {
                var a = this.words,
                    c = this.sigBytes;
                a[c >>> 2] &= 4294967295 << 32 - 8 * (c % 4);
                a.length = u.ceil(c / 4)
            },
            clone: function clone() {
                var a = t.clone.call(this);
                a.words = this.words.slice(0);
                return a
            },
            random: function random(a) {
                for (var c = [], e = 0; e < a; e += 4) {
                    c.push(4294967296 * u.random() | 0)
                }
                return new r.init(c, a)
            }
        }),
        w = d.enc = {},
        v = w.Hex = {
            stringify: function stringify(a) {
                var c = a.words;
                a = a.sigBytes;
                for (var e = [], j = 0; j < a; j++) {
                    var k = c[j >>> 2] >>> 24 - 8 * (j % 4) & 255;
                    e.push((k >>> 4).toString(16));
                    e.push((k & 15).toString(16))
                }
                return e.join("")
            },
            parse: function parse(a) {
                for (var c = a.length, e = [], j = 0; j < c; j += 2) {
                    e[j >>> 3] |= parseInt(a.substr(j, 2), 16) << 24 - 4 * (j % 8)
                }
                return new r.init(e, c / 2)
            }
        },
        b = w.Latin1 = {
            stringify: function stringify(a) {
                var c = a.words;
                a = a.sigBytes;
                for (var e = [], j = 0; j < a; j++) {
                    e.push(String.fromCharCode(c[j >>> 2] >>> 24 - 8 * (j % 4) & 255))
                }
                return e.join("")
            },
            parse: function parse(a) {
                for (var c = a.length, e = [], j = 0; j < c; j++) {
                    e[j >>> 2] |= (a.charCodeAt(j) & 255) << 24 - 8 * (j % 4)
                }
                return new r.init(e, c)
            }
        },
        x = w.Utf8 = {
            stringify: function stringify(a) {
                try {
                    return decodeURIComponent(escape(b.stringify(a)))
                } catch (c) {
                    throw Error("Malformed UTF-8 data")
                }
            },
            parse: function parse(a) {
                return b.parse(unescape(encodeURIComponent(a)))
            }
        },
        q = l.BufferedBlockAlgorithm = t.extend({
            reset: function reset() {
                this._data = new r.init();
                this._nDataBytes = 0
            },
            _append: function _append(a) {
                "string" == typeof a && (a = x.parse(a));
                this._data.concat(a);
                this._nDataBytes += a.sigBytes
            },
            _process: function _process(a) {
                var c = this._data,
                    e = c.words,
                    j = c.sigBytes,
                    k = this.blockSize,
                    b = j / (4 * k),
                    b = a ? u.ceil(b) : u.max((b | 0) - this._minBufferSize, 0);
                a = b * k;
                j = u.min(4 * a, j);
                if (a) {
                    for (var q = 0; q < a; q += k) {
                        this._doProcessBlock(e, q)
                    }
                    q = e.splice(0, a);
                    c.sigBytes -= j
                }
                return new r.init(q, j)
            },
            clone: function clone() {
                var a = t.clone.call(this);
                a._data = this._data.clone();
                return a
            },
            _minBufferSize: 0
        });
    l.Hasher = q.extend({
        cfg: t.extend(),
        init: function init(a) {
            this.cfg = this.cfg.extend(a);
            this.reset()
        },
        reset: function reset() {
            q.reset.call(this);
            this._doReset()
        },
        update: function update(a) {
            this._append(a);
            this._process();
            return this
        },
        finalize: function finalize(a) {
            a && this._append(a);
            return this._doFinalize()
        },
        blockSize: 16,
        _createHelper: function _createHelper(a) {
            return function (b, e) {
                return new a.init(e).finalize(b)
            }
        },
        _createHmacHelper: function _createHmacHelper(a) {
            return function (b, e) {
                return new n.HMAC.init(a, e).finalize(b)
            }
        }
    });
    var n = d.algo = {};
    return d
}(Math);
(function () {
    var u = CryptoJS,
        p = u.lib.WordArray;
    u.enc.Base64 = {
        stringify: function stringify(d) {
            var l = d.words,
                p = d.sigBytes,
                t = this._map;
            d.clamp();
            d = [];
            for (var r = 0; r < p; r += 3) {
                for (var w = (l[r >>> 2] >>> 24 - 8 * (r % 4) & 255) << 16 | (l[r + 1 >>> 2] >>> 24 - 8 * ((r + 1) % 4) & 255) << 8 | l[r + 2 >>> 2] >>> 24 - 8 * ((r + 2) % 4) & 255, v = 0; 4 > v && r + .75 * v < p; v++) {
                    d.push(t.charAt(w >>> 6 * (3 - v) & 63))
                }
            }
            if (l = t.charAt(64))
                for (; d.length % 4;) {
                    d.push(l)
                }
            return d.join("")
        },
        parse: function parse(d) {
            var l = d.length,
                s = this._map,
                t = s.charAt(64);
            t && (t = d.indexOf(t), -1 != t && (l = t));
            for (var t = [], r = 0, w = 0; w < l; w++) {
                if (w % 4) {
                    var v = s.indexOf(d.charAt(w - 1)) << 2 * (w % 4),
                        b = s.indexOf(d.charAt(w)) >>> 6 - 2 * (w % 4);
                    t[r >>> 2] |= (v | b) << 24 - 8 * (r % 4);
                    r++
                }
            }
            return p.create(t, r)
        },
        _map: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="
    }
})();
(function (u) {
    function p(b, n, a, c, e, j, k) {
        b = b + (n & a | ~n & c) + e + k;
        return (b << j | b >>> 32 - j) + n
    }

    function d(b, n, a, c, e, j, k) {
        b = b + (n & c | a & ~c) + e + k;
        return (b << j | b >>> 32 - j) + n
    }

    function l(b, n, a, c, e, j, k) {
        b = b + (n ^ a ^ c) + e + k;
        return (b << j | b >>> 32 - j) + n
    }

    function s(b, n, a, c, e, j, k) {
        b = b + (a ^ (n | ~c)) + e + k;
        return (b << j | b >>> 32 - j) + n
    }
    for (var t = CryptoJS, r = t.lib, w = r.WordArray, v = r.Hasher, r = t.algo, b = [], x = 0; 64 > x; x++) {
        b[x] = 4294967296 * u.abs(u.sin(x + 1)) | 0
    }
    r = r.MD5 = v.extend({
        _doReset: function _doReset() {
            this._hash = new w.init([1732584193, 4023233417, 2562383102, 271733878])
        },
        _doProcessBlock: function _doProcessBlock(q, n) {
            for (var a = 0; 16 > a; a++) {
                var c = n + a,
                    e = q[c];
                q[c] = (e << 8 | e >>> 24) & 16711935 | (e << 24 | e >>> 8) & 4278255360
            }
            var a = this._hash.words,
                c = q[n + 0],
                e = q[n + 1],
                j = q[n + 2],
                k = q[n + 3],
                z = q[n + 4],
                r = q[n + 5],
                t = q[n + 6],
                w = q[n + 7],
                v = q[n + 8],
                A = q[n + 9],
                B = q[n + 10],
                C = q[n + 11],
                u = q[n + 12],
                D = q[n + 13],
                E = q[n + 14],
                x = q[n + 15],
                f = a[0],
                m = a[1],
                g = a[2],
                h = a[3],
                f = p(f, m, g, h, c, 7, b[0]),
                h = p(h, f, m, g, e, 12, b[1]),
                g = p(g, h, f, m, j, 17, b[2]),
                m = p(m, g, h, f, k, 22, b[3]),
                f = p(f, m, g, h, z, 7, b[4]),
                h = p(h, f, m, g, r, 12, b[5]),
                g = p(g, h, f, m, t, 17, b[6]),
                m = p(m, g, h, f, w, 22, b[7]),
                f = p(f, m, g, h, v, 7, b[8]),
                h = p(h, f, m, g, A, 12, b[9]),
                g = p(g, h, f, m, B, 17, b[10]),
                m = p(m, g, h, f, C, 22, b[11]),
                f = p(f, m, g, h, u, 7, b[12]),
                h = p(h, f, m, g, D, 12, b[13]),
                g = p(g, h, f, m, E, 17, b[14]),
                m = p(m, g, h, f, x, 22, b[15]),
                f = d(f, m, g, h, e, 5, b[16]),
                h = d(h, f, m, g, t, 9, b[17]),
                g = d(g, h, f, m, C, 14, b[18]),
                m = d(m, g, h, f, c, 20, b[19]),
                f = d(f, m, g, h, r, 5, b[20]),
                h = d(h, f, m, g, B, 9, b[21]),
                g = d(g, h, f, m, x, 14, b[22]),
                m = d(m, g, h, f, z, 20, b[23]),
                f = d(f, m, g, h, A, 5, b[24]),
                h = d(h, f, m, g, E, 9, b[25]),
                g = d(g, h, f, m, k, 14, b[26]),
                m = d(m, g, h, f, v, 20, b[27]),
                f = d(f, m, g, h, D, 5, b[28]),
                h = d(h, f, m, g, j, 9, b[29]),
                g = d(g, h, f, m, w, 14, b[30]),
                m = d(m, g, h, f, u, 20, b[31]),
                f = l(f, m, g, h, r, 4, b[32]),
                h = l(h, f, m, g, v, 11, b[33]),
                g = l(g, h, f, m, C, 16, b[34]),
                m = l(m, g, h, f, E, 23, b[35]),
                f = l(f, m, g, h, e, 4, b[36]),
                h = l(h, f, m, g, z, 11, b[37]),
                g = l(g, h, f, m, w, 16, b[38]),
                m = l(m, g, h, f, B, 23, b[39]),
                f = l(f, m, g, h, D, 4, b[40]),
                h = l(h, f, m, g, c, 11, b[41]),
                g = l(g, h, f, m, k, 16, b[42]),
                m = l(m, g, h, f, t, 23, b[43]),
                f = l(f, m, g, h, A, 4, b[44]),
                h = l(h, f, m, g, u, 11, b[45]),
                g = l(g, h, f, m, x, 16, b[46]),
                m = l(m, g, h, f, j, 23, b[47]),
                f = s(f, m, g, h, c, 6, b[48]),
                h = s(h, f, m, g, w, 10, b[49]),
                g = s(g, h, f, m, E, 15, b[50]),
                m = s(m, g, h, f, r, 21, b[51]),
                f = s(f, m, g, h, u, 6, b[52]),
                h = s(h, f, m, g, k, 10, b[53]),
                g = s(g, h, f, m, B, 15, b[54]),
                m = s(m, g, h, f, e, 21, b[55]),
                f = s(f, m, g, h, v, 6, b[56]),
                h = s(h, f, m, g, x, 10, b[57]),
                g = s(g, h, f, m, t, 15, b[58]),
                m = s(m, g, h, f, D, 21, b[59]),
                f = s(f, m, g, h, z, 6, b[60]),
                h = s(h, f, m, g, C, 10, b[61]),
                g = s(g, h, f, m, j, 15, b[62]),
                m = s(m, g, h, f, A, 21, b[63]);
            a[0] = a[0] + f | 0;
            a[1] = a[1] + m | 0;
            a[2] = a[2] + g | 0;
            a[3] = a[3] + h | 0
        },
        _doFinalize: function _doFinalize() {
            var b = this._data,
                n = b.words,
                a = 8 * this._nDataBytes,
                c = 8 * b.sigBytes;
            n[c >>> 5] |= 128 << 24 - c % 32;
            var e = u.floor(a / 4294967296);
            n[(c + 64 >>> 9 << 4) + 15] = (e << 8 | e >>> 24) & 16711935 | (e << 24 | e >>> 8) & 4278255360;
            n[(c + 64 >>> 9 << 4) + 14] = (a << 8 | a >>> 24) & 16711935 | (a << 24 | a >>> 8) & 4278255360;
            b.sigBytes = 4 * (n.length + 1);
            this._process();
            b = this._hash;
            n = b.words;
            for (a = 0; 4 > a; a++) {
                c = n[a], n[a] = (c << 8 | c >>> 24) & 16711935 | (c << 24 | c >>> 8) & 4278255360
            }
            return b
        },
        clone: function clone() {
            var b = v.clone.call(this);
            b._hash = this._hash.clone();
            return b
        }
    });
    t.MD5 = v._createHelper(r);
    t.HmacMD5 = v._createHmacHelper(r)
})(Math);
(function () {
    var u = CryptoJS,
        p = u.lib,
        d = p.Base,
        l = p.WordArray,
        p = u.algo,
        s = p.EvpKDF = d.extend({
            cfg: d.extend({
                keySize: 4,
                hasher: p.MD5,
                iterations: 1
            }),
            init: function init(d) {
                this.cfg = this.cfg.extend(d)
            },
            compute: function compute(d, r) {
                for (var p = this.cfg, s = p.hasher.create(), b = l.create(), u = b.words, q = p.keySize, p = p.iterations; u.length < q;) {
                    n && s.update(n);
                    var n = s.update(d).finalize(r);
                    s.reset();
                    for (var a = 1; a < p; a++) {
                        n = s.finalize(n), s.reset()
                    }
                    b.concat(n)
                }
                b.sigBytes = 4 * q;
                return b
            }
        });
    u.EvpKDF = function (d, l, p) {
        return s.create(p).compute(d, l)
    }
})();
CryptoJS.lib.Cipher || function (u) {
    var p = CryptoJS,
        d = p.lib,
        l = d.Base,
        s = d.WordArray,
        t = d.BufferedBlockAlgorithm,
        r = p.enc.Base64,
        w = p.algo.EvpKDF,
        v = d.Cipher = t.extend({
            cfg: l.extend(),
            createEncryptor: function createEncryptor(e, a) {
                return this.create(this._ENC_XFORM_MODE, e, a)
            },
            createDecryptor: function createDecryptor(e, a) {
                return this.create(this._DEC_XFORM_MODE, e, a)
            },
            init: function init(e, a, b) {
                this.cfg = this.cfg.extend(b);
                this._xformMode = e;
                this._key = a;
                this.reset()
            },
            reset: function reset() {
                t.reset.call(this);
                this._doReset()
            },
            process: function process(e) {
                this._append(e);
                return this._process()
            },
            finalize: function finalize(e) {
                e && this._append(e);
                return this._doFinalize()
            },
            keySize: 4,
            ivSize: 4,
            _ENC_XFORM_MODE: 1,
            _DEC_XFORM_MODE: 2,
            _createHelper: function _createHelper(e) {
                return {
                    encrypt: function encrypt(b, k, d) {
                        return ("string" == typeof k ? c : a).encrypt(e, b, k, d)
                    },
                    decrypt: function decrypt(b, k, d) {
                        return ("string" == typeof k ? c : a).decrypt(e, b, k, d)
                    }
                }
            }
        });
    d.StreamCipher = v.extend({
        _doFinalize: function _doFinalize() {
            return this._process(!0)
        },
        blockSize: 1
    });
    var b = p.mode = {},
        x = function x(e, a, b) {
            var c = this._iv;
            c ? this._iv = u : c = this._prevBlock;
            for (var d = 0; d < b; d++) {
                e[a + d] ^= c[d]
            }
        },
        q = (d.BlockCipherMode = l.extend({
            createEncryptor: function createEncryptor(e, a) {
                return this.Encryptor.create(e, a)
            },
            createDecryptor: function createDecryptor(e, a) {
                return this.Decryptor.create(e, a)
            },
            init: function init(e, a) {
                this._cipher = e;
                this._iv = a
            }
        })).extend();
    q.Encryptor = q.extend({
        processBlock: function processBlock(e, a) {
            var b = this._cipher,
                c = b.blockSize;
            x.call(this, e, a, c);
            b.encryptBlock(e, a);
            this._prevBlock = e.slice(a, a + c)
        }
    });
    q.Decryptor = q.extend({
        processBlock: function processBlock(e, a) {
            var b = this._cipher,
                c = b.blockSize,
                d = e.slice(a, a + c);
            b.decryptBlock(e, a);
            x.call(this, e, a, c);
            this._prevBlock = d
        }
    });
    b = b.CBC = q;
    q = (p.pad = {}).Pkcs7 = {
        pad: function pad(a, b) {
            for (var c = 4 * b, c = c - a.sigBytes % c, d = c << 24 | c << 16 | c << 8 | c, l = [], n = 0; n < c; n += 4) {
                l.push(d)
            }
            c = s.create(l, c);
            a.concat(c)
        },
        unpad: function unpad(a) {
            a.sigBytes -= a.words[a.sigBytes - 1 >>> 2] & 255
        }
    };
    d.BlockCipher = v.extend({
        cfg: v.cfg.extend({
            mode: b,
            padding: q
        }),
        reset: function reset() {
            v.reset.call(this);
            var a = this.cfg,
                b = a.iv,
                a = a.mode;
            if (this._xformMode == this._ENC_XFORM_MODE) var c = a.createEncryptor;
            else c = a.createDecryptor, this._minBufferSize = 1;
            this._mode = c.call(a, this, b && b.words)
        },
        _doProcessBlock: function _doProcessBlock(a, b) {
            this._mode.processBlock(a, b)
        },
        _doFinalize: function _doFinalize() {
            var a = this.cfg.padding;
            if (this._xformMode == this._ENC_XFORM_MODE) {
                a.pad(this._data, this.blockSize);
                var b = this._process(!0)
            } else b = this._process(!0), a.unpad(b);
            return b
        },
        blockSize: 4
    });
    var n = d.CipherParams = l.extend({
        init: function init(a) {
            this.mixIn(a)
        },
        toString: function toString(a) {
            return (a || this.formatter).stringify(this)
        }
    }),
        b = (p.format = {}).OpenSSL = {
            stringify: function stringify(a) {
                var b = a.ciphertext;
                a = a.salt;
                return (a ? s.create([1398893684, 1701076831]).concat(a).concat(b) : b).toString(r)
            },
            parse: function parse(a) {
                a = r.parse(a);
                var b = a.words;
                if (1398893684 == b[0] && 1701076831 == b[1]) {
                    var c = s.create(b.slice(2, 4));
                    b.splice(0, 4);
                    a.sigBytes -= 16
                }
                return n.create({
                    ciphertext: a,
                    salt: c
                })
            }
        },
        a = d.SerializableCipher = l.extend({
            cfg: l.extend({
                format: b
            }),
            encrypt: function encrypt(a, b, c, d) {
                d = this.cfg.extend(d);
                var l = a.createEncryptor(c, d);
                b = l.finalize(b);
                l = l.cfg;
                return n.create({
                    ciphertext: b,
                    key: c,
                    iv: l.iv,
                    algorithm: a,
                    mode: l.mode,
                    padding: l.padding,
                    blockSize: a.blockSize,
                    formatter: d.format
                })
            },
            decrypt: function decrypt(a, b, c, d) {
                d = this.cfg.extend(d);
                b = this._parse(b, d.format);
                return a.createDecryptor(c, d).finalize(b.ciphertext)
            },
            _parse: function _parse(a, b) {
                return "string" == typeof a ? b.parse(a, this) : a
            }
        }),
        p = (p.kdf = {}).OpenSSL = {
            execute: function execute(a, b, c, d) {
                d || (d = s.random(8));
                a = w.create({
                    keySize: b + c
                }).compute(a, d);
                c = s.create(a.words.slice(b), 4 * c);
                a.sigBytes = 4 * b;
                return n.create({
                    key: a,
                    iv: c,
                    salt: d
                })
            }
        },
        c = d.PasswordBasedCipher = a.extend({
            cfg: a.cfg.extend({
                kdf: p
            }),
            encrypt: function encrypt(b, c, d, l) {
                l = this.cfg.extend(l);
                d = l.kdf.execute(d, b.keySize, b.ivSize);
                l.iv = d.iv;
                b = a.encrypt.call(this, b, c, d.key, l);
                b.mixIn(d);
                return b
            },
            decrypt: function decrypt(b, c, d, l) {
                l = this.cfg.extend(l);
                c = this._parse(c, l.format);
                d = l.kdf.execute(d, b.keySize, b.ivSize, c.salt);
                l.iv = d.iv;
                return a.decrypt.call(this, b, c, d.key, l)
            }
        })
}();
(function () {
    for (var u = CryptoJS, p = u.lib.BlockCipher, d = u.algo, l = [], s = [], t = [], r = [], w = [], v = [], b = [], x = [], q = [], n = [], a = [], c = 0; 256 > c; c++) {
        a[c] = 128 > c ? c << 1 : c << 1 ^ 283
    }
    for (var e = 0, j = 0, c = 0; 256 > c; c++) {
        var k = j ^ j << 1 ^ j << 2 ^ j << 3 ^ j << 4,
            k = k >>> 8 ^ k & 255 ^ 99;
        l[e] = k;
        s[k] = e;
        var z = a[e],
            F = a[z],
            G = a[F],
            y = 257 * a[k] ^ 16843008 * k;
        t[e] = y << 24 | y >>> 8;
        r[e] = y << 16 | y >>> 16;
        w[e] = y << 8 | y >>> 24;
        v[e] = y;
        y = 16843009 * G ^ 65537 * F ^ 257 * z ^ 16843008 * e;
        b[k] = y << 24 | y >>> 8;
        x[k] = y << 16 | y >>> 16;
        q[k] = y << 8 | y >>> 24;
        n[k] = y;
        e ? (e = z ^ a[a[a[G ^ z]]], j ^= a[a[j]]) : e = j = 1
    }
    var H = [0, 1, 2, 4, 8, 16, 32, 64, 128, 27, 54],
        d = d.AES = p.extend({
            _doReset: function _doReset() {
                for (var a = this._key, c = a.words, d = a.sigBytes / 4, a = 4 * ((this._nRounds = d + 6) + 1), e = this._keySchedule = [], j = 0; j < a; j++) {
                    if (j < d) e[j] = c[j];
                    else {
                        var k = e[j - 1];
                        j % d ? 6 < d && 4 == j % d && (k = l[k >>> 24] << 24 | l[k >>> 16 & 255] << 16 | l[k >>> 8 & 255] << 8 | l[k & 255]) : (k = k << 8 | k >>> 24, k = l[k >>> 24] << 24 | l[k >>> 16 & 255] << 16 | l[k >>> 8 & 255] << 8 | l[k & 255], k ^= H[j / d | 0] << 24);
                        e[j] = e[j - d] ^ k
                    }
                }
                c = this._invKeySchedule = [];
                for (d = 0; d < a; d++) {
                    j = a - d, k = d % 4 ? e[j] : e[j - 4], c[d] = 4 > d || 4 >= j ? k : b[l[k >>> 24]] ^ x[l[k >>> 16 & 255]] ^ q[l[k >>> 8 & 255]] ^ n[l[k & 255]]
                }
            },
            encryptBlock: function encryptBlock(a, b) {
                this._doCryptBlock(a, b, this._keySchedule, t, r, w, v, l)
            },
            decryptBlock: function decryptBlock(a, c) {
                var d = a[c + 1];
                a[c + 1] = a[c + 3];
                a[c + 3] = d;
                this._doCryptBlock(a, c, this._invKeySchedule, b, x, q, n, s);
                d = a[c + 1];
                a[c + 1] = a[c + 3];
                a[c + 3] = d
            },
            _doCryptBlock: function _doCryptBlock(a, b, c, d, e, j, l, f) {
                for (var m = this._nRounds, g = a[b] ^ c[0], h = a[b + 1] ^ c[1], k = a[b + 2] ^ c[2], n = a[b + 3] ^ c[3], p = 4, r = 1; r < m; r++) {
                    var q = d[g >>> 24] ^ e[h >>> 16 & 255] ^ j[k >>> 8 & 255] ^ l[n & 255] ^ c[p++],
                        s = d[h >>> 24] ^ e[k >>> 16 & 255] ^ j[n >>> 8 & 255] ^ l[g & 255] ^ c[p++],
                        t = d[k >>> 24] ^ e[n >>> 16 & 255] ^ j[g >>> 8 & 255] ^ l[h & 255] ^ c[p++],
                        n = d[n >>> 24] ^ e[g >>> 16 & 255] ^ j[h >>> 8 & 255] ^ l[k & 255] ^ c[p++],
                        g = q,
                        h = s,
                        k = t
                }
                q = (f[g >>> 24] << 24 | f[h >>> 16 & 255] << 16 | f[k >>> 8 & 255] << 8 | f[n & 255]) ^ c[p++];
                s = (f[h >>> 24] << 24 | f[k >>> 16 & 255] << 16 | f[n >>> 8 & 255] << 8 | f[g & 255]) ^ c[p++];
                t = (f[k >>> 24] << 24 | f[n >>> 16 & 255] << 16 | f[g >>> 8 & 255] << 8 | f[h & 255]) ^ c[p++];
                n = (f[n >>> 24] << 24 | f[g >>> 16 & 255] << 16 | f[h >>> 8 & 255] << 8 | f[k & 255]) ^ c[p++];
                a[b] = q;
                a[b + 1] = s;
                a[b + 2] = t;
                a[b + 3] = n
            },
            keySize: 8
        });
    u.AES = p._createHelper(d)
})();
var MD5 = function MD5(string) {
    function RotateLeft(lValue, iShiftBits) {
        return lValue << iShiftBits | lValue >>> 32 - iShiftBits
    }

    function AddUnsigned(lX, lY) {
        var lX4, lY4, lX8, lY8, lResult;
        lX8 = lX & 2147483648;
        lY8 = lY & 2147483648;
        lX4 = lX & 1073741824;
        lY4 = lY & 1073741824;
        lResult = (lX & 1073741823) + (lY & 1073741823);
        if (lX4 & lY4) {
            return lResult ^ 2147483648 ^ lX8 ^ lY8
        }
        if (lX4 | lY4) {
            if (lResult & 1073741824) {
                return lResult ^ 3221225472 ^ lX8 ^ lY8
            } else {
                return lResult ^ 1073741824 ^ lX8 ^ lY8
            }
        } else {
            return lResult ^ lX8 ^ lY8
        }
    }

    function F(x, y, z) {
        return x & y | ~x & z
    }

    function G(x, y, z) {
        return x & z | y & ~z
    }

    function H(x, y, z) {
        return x ^ y ^ z
    }

    function I(x, y, z) {
        return y ^ (x | ~z)
    }

    function FF(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(F(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b)
    }

    function GG(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(G(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b)
    }

    function HH(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(H(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b)
    }

    function II(a, b, c, d, x, s, ac) {
        a = AddUnsigned(a, AddUnsigned(AddUnsigned(I(b, c, d), x), ac));
        return AddUnsigned(RotateLeft(a, s), b)
    }

    function ConvertToWordArray(string) {
        var lWordCount;
        var lMessageLength = string.length;
        var lNumberOfWords_temp1 = lMessageLength + 8;
        var lNumberOfWords_temp2 = (lNumberOfWords_temp1 - lNumberOfWords_temp1 % 64) / 64;
        var lNumberOfWords = (lNumberOfWords_temp2 + 1) * 16;
        var lWordArray = Array(lNumberOfWords - 1);
        var lBytePosition = 0;
        var lByteCount = 0;
        while (lByteCount < lMessageLength) {
            lWordCount = (lByteCount - lByteCount % 4) / 4;
            lBytePosition = lByteCount % 4 * 8;
            lWordArray[lWordCount] = lWordArray[lWordCount] | string.charCodeAt(lByteCount) << lBytePosition;
            lByteCount++
        }
        lWordCount = (lByteCount - lByteCount % 4) / 4;
        lBytePosition = lByteCount % 4 * 8;
        lWordArray[lWordCount] = lWordArray[lWordCount] | 128 << lBytePosition;
        lWordArray[lNumberOfWords - 2] = lMessageLength << 3;
        lWordArray[lNumberOfWords - 1] = lMessageLength >>> 29;
        return lWordArray
    }

    function WordToHex(lValue) {
        var WordToHexValue = "",
            WordToHexValue_temp = "",
            lByte, lCount;
        for (lCount = 0; lCount <= 3; lCount++) {
            lByte = lValue >>> lCount * 8 & 255;
            WordToHexValue_temp = "0" + lByte.toString(16);
            WordToHexValue = WordToHexValue + WordToHexValue_temp.substr(WordToHexValue_temp.length - 2, 2)
        }
        return WordToHexValue
    }

    function Utf8Encode(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";
        for (var n = 0; n < string.length; n++) {
            var c = string.charCodeAt(n);
            if (c < 128) {
                utftext += String.fromCharCode(c)
            } else if (c > 127 && c < 2048) {
                utftext += String.fromCharCode(c >> 6 | 192);
                utftext += String.fromCharCode(c & 63 | 128)
            } else {
                utftext += String.fromCharCode(c >> 12 | 224);
                utftext += String.fromCharCode(c >> 6 & 63 | 128);
                utftext += String.fromCharCode(c & 63 | 128)
            }
        }
        return utftext
    }
    var x = Array();
    var k, AA, BB, CC, DD, a, b, c, d;
    var S11 = 7,
        S12 = 12,
        S13 = 17,
        S14 = 22;
    var S21 = 5,
        S22 = 9,
        S23 = 14,
        S24 = 20;
    var S31 = 4,
        S32 = 11,
        S33 = 16,
        S34 = 23;
    var S41 = 6,
        S42 = 10,
        S43 = 15,
        S44 = 21;
    string = Utf8Encode(string);
    x = ConvertToWordArray(string);
    a = 1732584193;
    b = 4023233417;
    c = 2562383102;
    d = 271733878;
    for (k = 0; k < x.length; k += 16) {
        AA = a;
        BB = b;
        CC = c;
        DD = d;
        a = FF(a, b, c, d, x[k + 0], S11, 3614090360);
        d = FF(d, a, b, c, x[k + 1], S12, 3905402710);
        c = FF(c, d, a, b, x[k + 2], S13, 606105819);
        b = FF(b, c, d, a, x[k + 3], S14, 3250441966);
        a = FF(a, b, c, d, x[k + 4], S11, 4118548399);
        d = FF(d, a, b, c, x[k + 5], S12, 1200080426);
        c = FF(c, d, a, b, x[k + 6], S13, 2821735955);
        b = FF(b, c, d, a, x[k + 7], S14, 4249261313);
        a = FF(a, b, c, d, x[k + 8], S11, 1770035416);
        d = FF(d, a, b, c, x[k + 9], S12, 2336552879);
        c = FF(c, d, a, b, x[k + 10], S13, 4294925233);
        b = FF(b, c, d, a, x[k + 11], S14, 2304563134);
        a = FF(a, b, c, d, x[k + 12], S11, 1804603682);
        d = FF(d, a, b, c, x[k + 13], S12, 4254626195);
        c = FF(c, d, a, b, x[k + 14], S13, 2792965006);
        b = FF(b, c, d, a, x[k + 15], S14, 1236535329);
        a = GG(a, b, c, d, x[k + 1], S21, 4129170786);
        d = GG(d, a, b, c, x[k + 6], S22, 3225465664);
        c = GG(c, d, a, b, x[k + 11], S23, 643717713);
        b = GG(b, c, d, a, x[k + 0], S24, 3921069994);
        a = GG(a, b, c, d, x[k + 5], S21, 3593408605);
        d = GG(d, a, b, c, x[k + 10], S22, 38016083);
        c = GG(c, d, a, b, x[k + 15], S23, 3634488961);
        b = GG(b, c, d, a, x[k + 4], S24, 3889429448);
        a = GG(a, b, c, d, x[k + 9], S21, 568446438);
        d = GG(d, a, b, c, x[k + 14], S22, 3275163606);
        c = GG(c, d, a, b, x[k + 3], S23, 4107603335);
        b = GG(b, c, d, a, x[k + 8], S24, 1163531501);
        a = GG(a, b, c, d, x[k + 13], S21, 2850285829);
        d = GG(d, a, b, c, x[k + 2], S22, 4243563512);
        c = GG(c, d, a, b, x[k + 7], S23, 1735328473);
        b = GG(b, c, d, a, x[k + 12], S24, 2368359562);
        a = HH(a, b, c, d, x[k + 5], S31, 4294588738);
        d = HH(d, a, b, c, x[k + 8], S32, 2272392833);
        c = HH(c, d, a, b, x[k + 11], S33, 1839030562);
        b = HH(b, c, d, a, x[k + 14], S34, 4259657740);
        a = HH(a, b, c, d, x[k + 1], S31, 2763975236);
        d = HH(d, a, b, c, x[k + 4], S32, 1272893353);
        c = HH(c, d, a, b, x[k + 7], S33, 4139469664);
        b = HH(b, c, d, a, x[k + 10], S34, 3200236656);
        a = HH(a, b, c, d, x[k + 13], S31, 681279174);
        d = HH(d, a, b, c, x[k + 0], S32, 3936430074);
        c = HH(c, d, a, b, x[k + 3], S33, 3572445317);
        b = HH(b, c, d, a, x[k + 6], S34, 76029189);
        a = HH(a, b, c, d, x[k + 9], S31, 3654602809);
        d = HH(d, a, b, c, x[k + 12], S32, 3873151461);
        c = HH(c, d, a, b, x[k + 15], S33, 530742520);
        b = HH(b, c, d, a, x[k + 2], S34, 3299628645);
        a = II(a, b, c, d, x[k + 0], S41, 4096336452);
        d = II(d, a, b, c, x[k + 7], S42, 1126891415);
        c = II(c, d, a, b, x[k + 14], S43, 2878612391);
        b = II(b, c, d, a, x[k + 5], S44, 4237533241);
        a = II(a, b, c, d, x[k + 12], S41, 1700485571);
        d = II(d, a, b, c, x[k + 3], S42, 2399980690);
        c = II(c, d, a, b, x[k + 10], S43, 4293915773);
        b = II(b, c, d, a, x[k + 1], S44, 2240044497);
        a = II(a, b, c, d, x[k + 8], S41, 1873313359);
        d = II(d, a, b, c, x[k + 15], S42, 4264355552);
        c = II(c, d, a, b, x[k + 6], S43, 2734768916);
        b = II(b, c, d, a, x[k + 13], S44, 1309151649);
        a = II(a, b, c, d, x[k + 4], S41, 4149444226);
        d = II(d, a, b, c, x[k + 11], S42, 3174756917);
        c = II(c, d, a, b, x[k + 2], S43, 718787259);
        b = II(b, c, d, a, x[k + 9], S44, 3951481745);
        a = AddUnsigned(a, AA);
        b = AddUnsigned(b, BB);
        c = AddUnsigned(c, CC);
        d = AddUnsigned(d, DD)
    }
    var temp = WordToHex(a) + WordToHex(b) + WordToHex(c) + WordToHex(d);
    return temp.toLowerCase()
};
var outHtmlJD = "<div class=\"LTplugin\">\n<div class=\"ltcontent\">\n    <li class=\"header\"><a href=\"http://www.letuilm.com/\" target=\"_blank\">乐推</a></li>\n    <div class=\"bar\">\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-1\"></i>最高佣金\n                <sp>--%</sp>\n            </div>\n            <div class=\"panel\">\n            <div id=\"panel-1\">\n                <ul class=\"info\">\n                    <li class=\"col-1\">最高佣金比例：</li>\n                    <li class=\"col-2\" id=\"hinumbig\">--</li>\n                    <li class=\"col-3\">%</li>\n                    <li class=\"col-4\">\n                        <button class=\"trans\"><i class=\"icon\"></i>联盟转链</button>\n                    </li>\n                </ul>\n                <div>30天推广：\n                    <sp id=\"ma-0\">--</sp>件&nbsp;丨&nbsp;30天支出佣金：\n                    <sp id=\"ma-1\">--</sp>元 </div>\n                <table>\n                    <thead>\n                        <tr>\n                            <th style=\"width: 28%;\">计划名称</th>\n                            <th style=\"width: 8%;\">状态</th>\n                            <th style=\"width: 16%;\">佣金比例</th>\n                            <th style=\"width: 16%;\">推广时间</th>\n                            <th style=\"width: 16%;\">优惠卷</th>\n                            <th style=\"width: 16%;\">操作</th>\n                        </tr>\n                    </thead>\n                    <tbody id=\"planheader\"></tbody>\n                </table>\n                <div> 在此填入计划申请理由:\n                    <input class=\"reason\" type=\"text\" />\n                </div>\n            </div>\n            </div>\n        </li>\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-5\"></i>比价\n                <sp id=\"hitrend\">--\n                    <sp>\n            </div>\n            <div class=\"panel\">\n            <div id=\"panel-2\">\n                <div id=\"historychart\" class=\"chartbox\"></div>\n            </div>\n            </div>\n        </li>\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-6\"></i>榜单</div>\n            <div class=\"panel\">\n                <div id=\"panel-3\" class=\"cab ltrank2\"></div>\n            </div>\n        </li>\n    </div>\n    <div class=\"tails\"><div class=\"tong close\"></div></div>\n</div>\n</div>";
var outHtmlTB = "<div class=\"LTplugin\">\n<div class=\"ltcontent\">\n    <li class=\"header\"><a href=\"http://www.letuilm.com/\" target=\"_blank\">乐推</a></li>\n    <div class=\"bar\">\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-1\"></i></div>\n            <div class=\"panel\">\n                <div id=\"panel-1\">\n                    <ul class=\"info\">\n                        <li class=\"col-1\">最高佣金比</li>\n                        <li class=\"col-2\">--</li>\n                        <li class=\"col-3\">%</li>\n                        <li class=\"col-5\">(￥--)</li>\n                        <li class=\"col-4\">\n                            <button class=\"trans\"><i class=\"icon\"></i>联盟转链</button>\n                            <button class=\"effic\"><i class=\"icon\"></i>高效转链</button>\n                        </li>\n                    </ul>\n                    <div>\n                       <mak>推</mak>30天推广量\n                        <sp id=\"ma-0\" class=\"bigger\">--</sp>件\n                        <nsp>|</nsp>\n                        <mak>佣</mak>30天支出佣金\n                        <sp id=\"ma-1\" class=\"bigger\">--</sp>元</div>\n                    <div>\n                    <mak class=\"cateId\">类目</mak><span id=\"ma-2\">--</span>\n                    </div>\n                    <div id=\"juspan\">\n                        <mak>聚</mak>聚划算销量\n                        <sp id=\"ma-3\" class=\"bigger\">--</sp>件\n                        <nsp>|</nsp>售罄率\n                        <sp id=\"ma-4\" class=\"bigger\">--%</sp>\n                    </div>\n                    <div id=\"shopspan\">\n                        <mak>粉</mak>店铺关注\n                        <sp id=\"ma-5\" class=\"bigger\">-</sp>\n                        <nsp>|</nsp>商品总量\n                        <sp id=\"ma-6\" class=\"bigger\">-</sp>件\n                        <nsp>|</nsp>开店日期\n                        <sp id=\"ma-7\" class=\"bigger\">-</sp>\n                    </div>\n                    <table class=\"board\">\n                        <thead>\n                            <tr>\n                                <th style=\"width: 26%;\">计划名称</th>\n                                <th style=\"width: 16%;\">佣金比例</th>\n                                <th style=\"width: 16%;\">佣金类型</th>\n                                <th style=\"width: 16%;\">人工审核</th>\n                                <th style=\"width: 14%;\">操作</th>\n                                <th style=\"width: 12%;\">详情</th>\n                            </tr>\n                        </thead>\n                        <tbody id=\"planheader\"></tbody>\n                    </table>\n                    <div id=\"noname\"> 在此填入计划申请理由:\n                        <input class=\"reason\" type=\"text\"> </div>\n                </div>\n            </div>\n        </li>\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-2\"></i>优惠券</div>\n            <div class=\"panel\">\n                <div id=\"panel-2\">\n                    <table class=\"board\">\n                        <thead>\n                            <tr>\n                                <th style=\"width: 30%;\">优惠卷</th>\n                                <th style=\"width: 10%;\">类型</th>\n                                <th style=\"width: 21%;\">有效期</th>\n                                <th style=\"width: 15%;\">领用量</th>\n                                <th style=\"width: 12%;\">复制</th>\n                                <th style=\"width: 12%;\">领券</th>\n                            </tr>\n                        </thead>\n                        <tbody id=\"couponheader\"></tbody>\n                    </table>\n                </div>\n            </div>\n        </li>\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-3\"></i>推广</div>\n            <div class=\"panel\">\n                <div id=\"panel-3\">\n                    <div class=\"sales-title\">\n                        <ul>\n                            <li class=\"salesli sales-active\">推广平台</li>\n                            <li class=\"salesli\">群传播记录</li>\n                            <li class=\"salesli\">销量轨迹</li>\n                        </ul>\n                    </div>\n                    <div class=\"sales-sales\">\n                        <ul> </ul>\n                    </div>\n                    <div id=\"saleschart\" class=\"chartbox2\"></div>\n                    <div class=\"lt_plats\">\n                        <ul>\n                            <li id=\"lt_plat-1\"></li>\n                            <li id=\"lt_plat-2\"></li>\n                            <li id=\"lt_plat-3\"></li>\n                            <li id=\"lt_plat-4\"></li>\n                        </ul>\n                    </div>\n                </div>\n            </div>\n        </li>\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-4\"></i>招商</div>\n            <div class=\"panel\">\n                <div id=\"panel-4\">\n                    <div class=\"ltuserbar\"></div>\n                    <div class=\"ltuserwork\"></div>\n                </div>\n            </div>\n        </li>\n        <li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-5\"></i>历史\n            </div>\n            <div class=\"panel\">\n                <div id=\"panel-5\">\n                <div id=\"historychart\" class=\"chartbox\"></div>\n                </div>\n            </div>\n        </li>\n         <li class=\"commands\">\n            <div class=\"fiche\">\n                <i class=\"icon t-0\" id=\"docW\" title=\"优质文案\"></i>\n                <i class=\"icon t-1\" id=\"tkyW\" title=\"淘客易记录\"></i>\n            </div>\n        </li>\n    </div>\n    <div class=\"tails\"><div class=\"tong close\"></div></div>\n</div>\n</div>";
// '<li class=\"lt_column\">\n            <div class=\"title\"><i class=\"icon c-6\"></i>榜单</div>\n            <div class=\"panel\">\n                <div id=\"panel-6\" class=\"cab ltrank2\"></div>\n            </div>\n        </li>\n'
var titleTB = `<div class="LT-Titler">\n
                      <div class="LT-TitlerThree">\n
                        <span class="lt_sycpk">乐推私域产品库</span>
                        <div class="jhsinfo" style="display:inline-block;">
                            <span class="isonline"></span>
                        </div>
                    </div>
                    <div class="LT-TitlerFour">\n
                        <span class="lt_spgtcs">商品沟通次数</span>
                        <div class="jhsinfo" style="display:inline-block;">
                            <span class="gtcs">沟通次数:</span>
                            <span class="zhgtsj">最后沟通时间:</span>
                        </div>
                    </div>
                    <div class="LT-TitlerFive">\n
                        <span class="lt_sdzt">上单状态</span>
                        <div class="jhsinfo" style="display:inline-block;">
                            <span class="ksd"></span>
                            <span class="sqyj">上期佣金:</span>
                            <span class="sqjhj">上期券后价:</span>
                        </div>
                    </div>
                    <div class="LT-TitlerOne">\n
                        <span class="gjz">关键字</span>
                        <span class="titlebar" data-type="tb">
                            <div class="tbpc lt_title">淘宝PC(<em class="em_red">0</em>)</div>
                            <div class="LT-TitlerTbpc poab"></div>
                        </span>
                        <span class="titlebar" data-type="p4p_tb">
                            <div class="tbpcztc lt_title">淘宝PC直通车(<em class="em_red">0</em>)</div>
                            <div class="LT-TitlerTbztc poab"></div>
                        </span>
                        <span class="titlebar" data-type="h5">
                            <div class="wx lt_title">无线(<em class="em_red">0</em>)</div>
                            <div class="LT-TitlerWx poab"></div>
                        </span>
                        <span class="titlebar" data-type="p4p_h5">
                            <div class="wxztc lt_title">无线直通车(<em class="em_red">0</em>)</div>
                            <div class="LT-TitlerWxztc poab"></div>
                        </span>
                    </div>
                    <div class="LT-TitlerTwo">\n
                        <span class="jhs">聚划算</span>
                        <div class="jhsinfo" style="display:inline-block;">
                        <span class="jhsxl">聚划算销量:</span>
                        <span class="gql">告罄率:</span>
                        </div>
                    </div>
                    <div class="LT-TitlerSix">
                         <div class="spreads">\n 
                            <ul>\n                            
                                <li id="spread-1"></li>\n
                                <li id="spread-2"></li>\n                            
                                <li id="spread-3"></li>\n                            
                                <li id="spread-4"></li>\n                        
                            </ul>\n                    
                        </div>\n 
                    </div>
               </div>`
var X5url = '',
    IsLogin = false,
    tzTimer, aliContact = {},
    layFlag = false,
    $$time = 0;
var $_userinfo = {
    lt_type: 0,
    lt_dom: '',
    lt_host: '',
    lt_token: '',
    lt_stamp: 0,
    lt_uid: '',
    lt_pwd: '',
    lt_tzname: ''
};
var couponurls = '';
var newrate = ''; //佣金
var isEmpty = function isEmpty(obj) {
    if (typeof obj == "undefined" || obj == null || obj == "") {
        return true
    } else {
        return false
    }
};
var validate = function validate(params) {
    var arr = Object.keys(params);
    return arr.length != 0
};
var rd = function rd(n, m) {
    return Math.floor(Math.random() * (m - n + 1) + n)
};
var checkNum = function checkNum(fnum) {
    return parseFloat(parseInt(fnum)) == fnum ? parseInt(fnum) : fnum
};
var urlParam = function urlParam(data) {
    var str = '';
    var index = 0;
    var por = [];
    for (var key in data) {
        por.push(key + "=" + data[key])
    }
    por.sort();
    for (var _key in por) {
        str = "" + str + (index === 0 ? '' : '&') + por[_key];
        index++
    }
    return str
};
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,
        "d+": this.getDate(),
        "h+": this.getHours(),
        "m+": this.getMinutes(),
        "s+": this.getSeconds(),
        "q+": Math.floor((this.getMonth() + 3) / 3),
        "S": this.getMilliseconds()
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length))
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length))
        }
    }
    return fmt
};
//获取商品信息
var libCollect = {
    getItemId: function getItemId() {
        var t = window.location,
            e = "";
        switch (t.host) {
            case "detail.ju.taobao.com":
                e = /[\?|&]item_id=(\d+)/.exec(t)[1];
                break;
            case "world.tmall.com":
            case "world.taobao.com":
                e = /\/(\d+)\.htm/.exec(t)[1];
                break;
            default:
                /[\?|&]id=(\d+)/.exec(t) && (e = /[\?|&]id=(\d+)/.exec(t)[1])
        }
        return e
    },
    getSellerId: function getSellerId() {
        var t = window.location.host,
            e = "";
        switch (t) {
            case "detail.ju.taobao.com":
                e = $(".J_RightRecommend").attr("data-sellerid");
                break;
            case "chaoshi.detail.tmall.com":
                var n = $("#J_SellerInfo").attr("data-url"),
                    i = n.match(/user_num_id=(\d+)/g);
                e = String(i).split("=")[1];
                break;
            case "world.taobao.com":
                var r = $("#J_listBuyerOnView").attr("data-api"),
                    o = r.match(/seller_num_id=(\d+)/g);
                e = String(o).split("=")[1];
                break;
            default:
                var a = $("meta[name=microscope-data]").attr("content");
                a && (e = /userid=(\d+)/.exec(a)[1])
        }
        return e
    },
    getCouponId: function getCouponId(t) {
        return (/[&|?]activity_?[i|I]d=(\w+)/.exec(t)[1])
    },
    getUlandE: function getUlandE(t) {
        return (/[&|?]e=(\w+)/.exec(t)[1])
    },
    getCategoryId: function getCategoryId(m) {
        var e = new RegExp("category=item%5f(\\d+)|categoryId=(\\d+)", "g");
        var n = e.exec(m);
        var o = null;
        if (null != n) {
            if (n[1]) o = n[1];
            if (n[2]) o = n[2]
        }
        return null != o ? o : null
    },
    getEventId: function getEventId(t) {
        return (/[&|?]eventId=(\w+)/.exec(t)[1])
    },
    getSkuId: function getSkuId() {
        return (/(\d+).html/.exec(window.location.href)[1])
    },
    getQueryString: function getQueryString(t, m) {
        var e = new RegExp("[&|?]" + t + "=(\\w+)", "g");
        var n = e.exec(m);
        return null != n ? unescape(n[1]) : null
    },
    getSimpeLink: function getSimpeLink(t) {
        var id = libCollect.getItemId(t);
        var host = t.substr(0, t.indexOf("?"));
        return id && host ? host + "?id=" + id : null
    },
    openWin: function openWin(t) {
        var e = (document.body.offsetWidth - 400) / 2;
        window.open(t, "_blank", "width=400,height=500,top=200,left=" + e)
    },
    strContent: function strContent(s, s1, s2) {
        var n1 = s.indexOf(s1, 0) + s1.length;
        var n2 = s.indexOf(s2, n1);
        return s.substring(n1, n2)
    },
    //获取商品名称
    getGoodsName: function getGoodsName() {
        var t = window.location,
            e = "";
        switch (t.host) {
            case 'https://detail.tmall.com/':
                e = $('.tb-detail-hd').find('h1').text().trim();
                break;
            default:
                e = $('.tb-detail-hd').find('h1').text().trim();
        }
        return e;
    },
    //获取店铺名称
    getShopName: function getShopName() {
        var t = window.location,
            e = "";
        switch (t.host) {
            case 'https://detail.tmall.com/':
                e = $('.slogo-shopname').children().text()
                break;
            default:
                e = $('.slogo-shopname').children().text()
        }
        return e;
    },
    //获取店铺名称
    getShopId: function getShopId() {
        var t = window.location,
            e = "";
        switch (t.host) {
            case 'https://detail.tmall.com/':
                e = $('#LineZing').attr("shopid")
                break;
            default:
                e = $('#LineZing').attr("shopid")
        }
        return e;
    },
    getUserName: function getUserName() {
        var t = window.location,
            e = "";
        switch (t.host) {
            case 'https://detail.tmall.com/':
                e = $('.sn-user-nick.j_UserNick.j_Username').text()
                break;
            default:
                e = $('.sn-user-nick.j_UserNick.j_Username').text()
        }
        return e;
        // sn-login
    },
    //读取cookie
    readCookie: function readCookie(cname) {
        var name = cname + "=";
        var ca = document.cookie.split(';');
        for (var i = 0; i < ca.length; i++) {
            var c = ca[i].trim();
            if (c.indexOf(name) == 0) {
                return c.substring(name.length, c.length);
            }
        }
        return "";
    },
    // 写入cookie
    writeCookie: function writeCookie(name, value, hours) {
        var expire = "";
        if (hours != null) {
            expire = new Date((new Date()).getTime() + hours * 3600000);
            expire = "; expires=" + expire.toGMTString();
        }
        document.cookie = name + "=" + escape(value) + expire;
    },
    // 删除cookie
    delcookie: function delcookie(name) {
        document.cookie = name + "=;expires=" + (new Date(0)).toGMTString();
    },
    // 查询佣金
    getrate: function getrate() {
        var url = 'http://hs.taokezhushou.com/v1/plan/get?goods_id=' + libCollect.getItemId()
        bgWork.get(url, '', function (sign, res) {

            console.log('佣金返回-01-', 1, res)
            if (res.status == "SUCCESS") {
                newrate = parseInt(res.data.commission_rate) / 100;

                console.log('佣金返回-1-', newrate, res)
                return parseInt(res.data.commission_rate) / 100
            } else {
                return ''
            }
        })
    },
};
//弹窗
var dialog = {
    msg: function msg(t) {
        layer.msg(t, {
            zIndex: 999999998 + 1,
            time: 2000
        })
    },
    box: function box(o) {
        layer.open({
            type: 1,
            shade: false,
            tite: o.title,
            area: [o.width, o.height],
            maxmin: false,
            content: o.content,
            zIndex: 99999999 + 1,
            end: function end() {
                layFlag = false
            }
        })
    },
    iframe: function iframe(o) {
        layer.open({
            type: 2,
            title: o.title,
            shadeClose: true,
            maxmin: false,
            area: [o.width, o.length],
            content: o.url,
            zIndex: 99999999 + 1
        })
    },
    tip: function tip(t) {
        layer.tips(t.text, t.tag, {
            tips: [1, '#E73828'],
            time: 2000
        })
    },
    load: function load() {
        layer.load(0, {
            shade: false,
            time: 2 * 1000,
            zIndex: 99999999 + 1
        })
    }
};
//配置域名 选择相应的类名
var webs = [{
    url: "detail.liangxinyao.com",
    dom: ".tm-delivery-panel",
    price: ".tm-promo-price",
    method: "append"
}, {
    url: "detail.tmall.com",
    dom: ".tb-meta",
    price: ".tm-promo-price",
    method: "after",
    dom2: "#detail",
    method2: "prepend",
}, {
    url: "detail.yao.95095.com",
    dom: ".tb-detail-hd",
    price: ".tm-promo-price",
    method: "before"
}, {
    url: "world.tmall.com",
    dom: ".tb-meta",
    price: ".tm-promo-price",
    method: "after",
    dom2: "#detail",
    method2: "prepend",
}, {
    url: "chaoshi.detail.tmall.com",
    dom: ".tb-meta",
    price: ".tm-promo-price",
    method: "after",
    dom2: "#detail",
    method2: "prepend",
}, {
    url: "item.taobao.com",
    dom: ".sep-line",
    price: [".tb-promo-price", ".tb-property-cont"],
    method: "after",
    dom2: "#detail",
    method2: "prepend",
}, {
    url: "detail.ju.taobao.com",
    dom: ".description",
    price: ".J_actPrice",
    method: "after"
}, {
    url: "detail.tmall.hk",
    dom: ".tb-meta",
    price: ".tm-promo-price",
    method: "after",
    dom2: "#detail",
    method2: "prepend",
}, {
    url: "item.jd.com",
    dom: "#choose-btns",
    price: ".p-price",
    method: "before"
}];
//不同域名追加dom
var webWork = {
    isShow: function isShow() {
        var turl = window.location.host,
            index = webs.findIndex(function (item) {
                return item.url === turl
            });
        return -1 !== index
    },
    showOut: function showOut(thtml) {
        var turl = window.location.host,
            element = webs.find(function (item) {
                return item.url === turl
            });
        if (element) {
            // console.log('element',element)
            switch (element.method) {
                case "append":
                    $(element.dom).append(thtml), $("#detail").children("div:first").css("zIndex", "1998");
                    $(element.price).attr("contenteditable", "true");
                    break;
                case "after":
                    $(element.dom).after(thtml);
                    $(element.price).attr("contenteditable", "true");
                    break;
                case "before":
                    $(element.dom).before(thtml);
                    if (Array.isArray(element.price)) {
                        for (var i in element.price) {
                            $(element.price[i]).attr("contenteditable", "true")
                        }
                    } else $(element.price).attr("contenteditable", "true");
                    break
            }
        }
    },
    showOut2: function showOut2(thtml) {
        var turl = window.location.host,
            element = webs.find(function (item) {
                return item.url === turl
            });
        if (element) {
            // console.log('element', element)
            switch (element.method2) {
                case "prepend":
                    // console.log('element.dom2', element.dom2)
                    // console.log('thtml',thtml)
                    $(element.dom2).prepend(thtml);
                    // $("#detail").children("div:first").css("zIndex", "1998");
                    // $(element.price).attr("contenteditable", "true");
                    break;
                case "append":
                    // console.log('element.dom2', element.dom2)
                    // console.log('thtml',thtml)
                    $(element.dom2).append(thtml);
                    // $("#detail").children("div:first").css("zIndex", "1998");
                    // $(element.price).attr("contenteditable", "true");
                    break;
                case "after":
                    $(element.dom2).after(thtml);
                    $(element.price).attr("contenteditable", "true");
                    break;
                case "before":
                    $(element.dom2).before(thtml);
                    if (Array.isArray(element.price)) {
                        for (var i in element.price) {
                            $(element.price[i]).attr("contenteditable", "true")
                        }
                    } else $(element.price).attr("contenteditable", "true");
                    break
            }
        }
    }
};
//请求方式
var bgWork = {
    get: function get(t, e, n) {
        chrome.runtime.sendMessage({
            type: "get",
            url: t,
            dataType: e
        }, function (t) {
            var e = t.status,
                i = t.result;
            e ? n(null, i) : n(i)
        })
    },
    get2: function get(t, p, e, n) {
        chrome.runtime.sendMessage({
            type: "get",
            url: t,
            params: p,
            dataType: e
        }, function (t) {
            var e = t.status,
                i = t.result;
            e ? n(null, i) : n(i)
        })
    },
    post: function post(t, e, n, i) {
        chrome.runtime.sendMessage({
            url: t,
            data: e,
            dataType: n,
            type: "post",
        }, function (t) {
            var e = t.status,
                n = t.result;
            e ? i(null, n) : i(n)
        })
    },
    webquest: function webquest(t, e, n, k, i) {
        chrome.runtime.sendMessage({
            type: "webquest",
            method: e,
            data: n,
            token: k,
            url: t
        }, function (t) {
            var e = t.status,
                n = t.result;
            e ? i(null, n) : i(n)
        })
    },
    postjson: function postjson(t, e, i) {
        chrome.runtime.sendMessage({
            type: "postjson",
            data: e,
            url: t
        }, function (t) {
            var e = t.status,
                n = t.result;
            e ? i(null, n) : i(n)
        })
    },
    getToken: function getToken(t) {
        chrome.runtime.sendMessage({
            type: "cookie",
            url: "https://alimama.com/",
            name: "_tb_token_"
        }, function (e) {
            t(null, e)
        })
    },
    getCookie: function getCookie(t, e, n) {
        chrome.runtime.sendMessage({
            type: "cookie",
            url: t,
            name: e
        }, function (t) {
            n(null, t)
        })
    },
    getCookies: function getCookies(u, t) {
        chrome.runtime.sendMessage({
            type: "allCookie",
            url: u
        }, function (e) {
            t(null, e)
        })
    },
    getSettings: function getSettings(k, t) {
        chrome.runtime.sendMessage({
            type: "getSetting",
            key: 'LTplugin_' + k
        }, function (e) {
            t(e == '' ? null : e)
        })
    },
    setSettings: function setSettings(k, v) {
        chrome.runtime.sendMessage({
            type: "setSetting",
            key: 'LTplugin_' + k,
            value: v
        }, function (e) { })
    },
    getVersion: function getVersion(t) {
        chrome.runtime.sendMessage({
            type: "getversion"
        }, function (e) {
            t(e)
        })
    }
};
var jdPlan = {
    ratelist: new Array(),
    goodSearch: function goodSearch(cb) {
        var postdata = {
            pageNo: 1,
            pageSize: 60,
            searchUUID: "",
            data: {
                bonusIds: null,
                categoryId: null,
                cat2Id: null,
                cat3Id: null,
                deliveryType: 0,
                fromCommissionRatio: null,
                toCommissionRatio: null,
                fromPrice: null,
                toPrice: null,
                hasCoupon: 0,
                isHot: null,
                isPinGou: 0,
                isZY: 0,
                isCare: 0,
                lock: 0,
                orientationFlag: 0,
                sort: null,
                sortName: null,
                key: window.location.href,
                searchType: "st1",
                keywordType: "kt1"
            }
        };
        bgWork.postjson("https://union.jd.com/api/goods/search", JSON.stringify(postdata), function (sign, res) {
            if (!sign && res && res.hasOwnProperty("data") && res.data.unionGoods.length > 0) {
                res.data.unionGoods[0][0].skuId == parseInt(libCollect.getSkuId()) ? cb(null, res.data.unionGoods[0][0]) : cb("没有找到京东联盟内此产品")
            } else if (!sign && res && res.message) cb(res.message);
            else cb("计划获取失败")
        })
    },
    queryPlanList: function queryPlanList(cb) {
        bgWork.get("https://union.jd.com/api/plan/queryPlanList?skuId=" + libCollect.getSkuId(), "json", function (sign, res) {
            !sign && res && res.hasOwnProperty("data") ? cb(null, res.data) : cb("计划获取失败")
        })
    },
    doing: function doing() {
        jdPlan.goodSearch(function (flag, obj) {
            if (!flag && obj) {
                $("#ma-0").text(obj.inOrderCount30Days);
                $("#ma-1").text(obj.inOrderComm30Days);
                jdPlan.ratelist.push(obj.wlCommissionRatio);
                $(".info").children(".col-2").text(obj.wlCommissionRatio);
                $(".c-1").parent().children("sp").text(obj.wlCommissionRatio + '%');
                jdPlan.showTable({
                    rate: obj.wlCommissionRatio + "%",
                    name: "通用计划",
                    pid: 0,
                    isLocked: false,
                    start: "",
                    end: "",
                    coupon: obj.hasCoupon > 0 ? "满" + obj.couponQuota + "减" + obj.couponDiscount : "-",
                    couponurl: obj.couponLink,
                    check: "无需审核"
                })
            } else {
                jdPlan.showTableLogin();
                $(".c-1").parent().children("sp").text('请先登录京东联盟')
            }
        });
        jdPlan.queryPlanList(function (flag, list) {
            if (!flag && list && Array.isArray(list)) {
                for (var i = 0; i < list.length; i++) {
                    item = list[i];
                    jdPlan.ratelist.push(item.maxWlCommissionRatio);
                    jdPlan.showTable({
                        rate: item.minWlCommissionRatio == item.maxWlCommissionRatio ? item.minWlCommissionRatio + "%" : item.minWlCommissionRatio + "-" + item.maxWlCommissionRatio + "%",
                        name: item.planName,
                        pid: item.planId,
                        isLocked: item.isLocked > 0 ? true : false,
                        start: Date.parse(new Date(item.startTime)),
                        end: Date.parse(new Date(item.endTime)),
                        coupon: item.hasCoupon > 0 ? item.couponInfo : "-",
                        couponurl: "",
                        check: item.checkTypeStr
                    })
                }
                var nums = jdPlan.ratelist.sort(function (a, b) {
                    return b - a
                });
                $(".info").children(".col-2").text(nums[0]);
                $(".c-1").parent().children("sp").text(nums[0] + '%')
            }
        })
    },
    showTable: function showTable(item) {
        var name = item.name,
            pid = item.pid,
            locked = item.isLocked ? "锁定" : "",
            rate = item.rate,
            time = item.start + item.end != '' ? new Date(item.start).format("MM-dd") + " ~ " + new Date(item.end).format("MM-dd") : '',
            couponinfo = item.coupon == "" ? "" : item.coupon,
            couponurl = item.couponurl,
            check = item.check;
        var tabtxt = "<tr><td><a class=\"jplanwork\" id=\"jdpid-" + pid + "\">" + name + "</a></td><td>" + locked + "</td><td>" + rate + "</td><td>" + time + "</td><td><a href=\"" + couponurl + "\" target=\"_blank\">" + couponinfo + "</a></td><td>" + check + "</td></tr>";
        $("#planheader").append(tabtxt)
    },
    showTableLogin: function showTableLogin() {
        var warring = '<tr><td colspan="6" class="center"><a class="loginwarring">登陆京东联盟后才能看见详细计划喔。<br>点我去登录京东联盟</a></td></tr>';
        $("#planheader").append(warring)
    }
};
var planWork = {
    getUnionPubContextInfo: function getUnionPubContextInfo(cb) {
        bgWork.get("https://pub.alimama.com/common/getUnionPubContextInfo.json", "json", function (sign, res) {
            if (!sign && res && !res.data.hasOwnProperty("noLogin")) {
                cb(null, {
                    login: !res.data.noLogin,
                    ip: res.data.ip
                })
            } else cb("getUnionPubContextInfo失败")
        })
    },
    getSuperSearchInfo: function getSuperSearchInfo(cb) {
        nodeWork.superSearch(function (sign, res) {
            if (!sign && res) {
                var dt = res;
                dt ? cb(null, {
                    tkSales: dt.tk_total_sales,
                    tkCommi: dt.tk_total_commi,
                    rebate: dt.zk_final_price,
                    sellerId: dt.seller_id,
                    shopName: dt.shop_title,
                    cateName: dt.level_one_category_name + "->" + dt.category_name,
                    campObj: {
                        id: 0,
                        type: dt.commission_type,
                        rate: dt.commission_rate
                    },
                    coupon: {
                        applyAmount: dt.coupon_start_fee,
                        amount: dt.coupon_amount,
                        tite: "满" + dt.coupon_start_fee + "减" + dt.coupon_amount,
                        total: dt.coupon_total_count,
                        receive: dt.coupon_total_count - dt.coupon_remain_count,
                        surplus: dt.coupon_remain_count,
                        couponType: 3
                    }
                }) : cb("没有数据")
            } else cb("nodework出现问题")
        })
    },
    getDingdanxiaDetail: function getDingdanxiaDetail(cb) {
        var data = {
            apikey: 'cE7DPwdtVEfvvqNok6JJZXmVCvGzxA2A',
            q: encodeURIComponent(window.location.href)
        };
        var url = "http://api.tbk.dingdanxia.com/tbk/super_search?";
        bgWork.get(url + urlParam(data), "json", function (sign, res) {
            if (!sign && res) {
                var dt = res.data[0];
                dt ? cb(null, {
                    tkSales: dt.tk_total_sales,
                    tkCommi: dt.tk_total_commi,
                    rebate: dt.zk_final_price,
                    sellerId: dt.seller_id,
                    shopName: dt.shop_title,
                    cateName: dt.level_one_category_name + "->" + dt.category_name,
                    campObj: {
                        id: 0,
                        type: dt.commission_type,
                        rate: dt.commission_rate
                    },
                    coupon: {
                        applyAmount: dt.coupon_start_fee,
                        amount: dt.coupon_amount,
                        tite: "满" + dt.coupon_start_fee + "减" + dt.coupon_amount,
                        total: dt.coupon_total_count,
                        receive: dt.coupon_total_count - dt.coupon_remain_count,
                        surplus: dt.coupon_remain_count,
                        couponType: 3
                    }
                }) : cb("没有数据")
            } else cb("订单侠接口出现问题")
        })
    },
    getOptimusMaterial: function getOptimusMaterial(tbtoken, cb) {
        var timestmp = Date.now();
        var turl = "https://pub.alimama.com/openapi/json2/1/gateway.unionpub/optimus.material.json?t=" + timestmp + "&_tb_token_=" + tbtoken;
        var dataobj = {
            floorId: "20392",
            pageNum: 0,
            pageSize: 60,
            refpid: "mm_14831782_0_0",
            variableMap: {
                fn: "search",
                _t: timestmp,
                q: window.location.href
            }
        };
        var datastr = "_data_=" + encodeURIComponent(JSON.stringify(dataobj));
        bgWork.post(turl, datastr, "json", function (sign, obj) {
            if (!sign && obj && obj.hasOwnProperty("model") && obj.success) {
                var dt = obj.model.recommend.resultList[0],
                    cmp = dt.tkSpecialCampaignIdRateMap,
                    spec = dt.udf_temp_store;
                if ((typeof dt === "undefined" ? "undefined" : _typeof(dt)) == "object") {
                    var pgk = {
                        tkSales: dt.tkTotalSales,
                        tkCommi: null,
                        rebate: dt.priceAfterCoupon,
                        sellerId: dt.sellerId,
                        shopName: dt.shopTitle,
                        campObj: {
                            id: 0,
                            type: spec.campaignType,
                            rate: spec.commissionRate
                        }
                    };
                    if (dt.hasOwnProperty("couponAmount")) {
                        var coupon = {
                            applyAmount: dt.price,
                            amount: dt.couponAmount,
                            tite: "满" + dt.price + "减" + dt.couponAmount,
                            total: dt.couponTotalCount,
                            receive: dt.couponSendCount,
                            surplus: dt.couponRemainCount,
                            couponType: 3
                        };
                        pgk.coupon = coupon
                    }
                    cb(null, pgk)
                } else cb('看上去是要喝水了呢')
            } else cb('没有找到淘客信息')
        })
    },
    getTbkPrivilege: function getTbkPrivilege(cb) {
        console.log('newrate', newrate)
        var postdata = {
            goods_id: libCollect.getItemId()
        };
        bgWork.post("http://tc-tz.yiquntui.com/api/token", urlParam(postdata), '', function (sign, tokenRes) {
            var url = "http://tc-tz.yiquntui.com/api/getmax?goods_id=" + libCollect.getItemId() + '&token=' + tokenRes.data.token + '&time=' + tokenRes.data.time; //之前连接
            var newrateurl = 'http://hs.taokezhushou.com/v1/plan/get?goods_id=' + libCollect.getItemId() //检测佣金新连接
            bgWork.get(url, 'json', function (sign, res) {
                let sign2 = false,
                    oldres = res;
                bgWork.get(newrateurl, '', function (sign, res2) {
                    newrate = parseInt(res2.data.commission_rate) / 100;
                    if (!sign2 && oldres && _typeof(oldres.data) == "object") {
                        var dt = oldres.data;
                        var rate_wl = parseFloat(dt.max_commission_rate_wl),
                            rate_hr = parseFloat(dt.max_commission_rate);
                        rate_wl = isNaN(rate_wl) ? 0 : rate_wl;
                        rate_hr = isNaN(rate_hr) ? 0 : rate_hr;
                        var rate = {
                            // commissionRate: rate_wl > rate_hr ? rate_wl : rate_hr,//(2020-10-24 更换为下面检测佣金返回)
                            commissionRate: newrate,
                            categoryId: dt.category_id
                        };
                        if (dt.hasOwnProperty("wuliao") > 0) {
                            rate.tkObj = {
                                tkSales: dt.wuliao.tk_total_sales,
                                tkCommi: dt.wuliao.tk_total_commi,
                                cateName: dt.wuliao.level_one_category_name + "->" + dt.wuliao.category_name
                            }, rate.campObj = {
                                id: 0,
                                type: dt.wuliao.commission_type,
                                // rate: parseFloat(dt.wuliao.commission_rate) * 100 //(2020-10-24 更换为下面检测佣金返回)
                                rate: newrate
                            }
                        }
                        if (dt.hasOwnProperty("coupon_info") > 0) {
                            var coupon = {
                                receive: dt.coupon_total_count - dt.coupon_remain_count,
                                surplus: dt.coupon_remain_count,
                                total: dt.coupon_total_count,
                                url: null,
                                title: dt.coupon_info.replace(/元/g, ''),
                                start: Date.parse(new Date(dt.coupon_start_time)),
                                end: Date.parse(new Date(dt.coupon_end_time)),
                                type: 3
                            };
                            cb(null, rate, coupon)
                        } else cb(null, rate, "没有优惠卷")
                    } else cb("可能出现了错误")
                });
            })
        });

    },
    getDirectionalPlan: function getDirectionalPlan(tbtoken, cb) {
        var timestmp = Date.now();
        var turl = "https://pub.alimama.com/pubauc/getCommonCampaignByItemId.json?t=" + timestmp + "&_tb_token_=" + tbtoken + "&itemId=" + libCollect.getItemId();
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res && res.ok && res.hasOwnProperty("data")) {
                var obs = [];
                res.data.length > 0 && res.data.map(function (item) {
                    obs.push({
                        campaignName: item.CampaignName,
                        campaignId: item.CampaignID,
                        needApply: item.Properties,
                        exist: item.Exist,
                        existStatus: item.ExistStatus,
                        shopkeeperId: item.ShopKeeperID,
                        avgCommissionRate: item.AvgCommission.substr(0, item.AvgCommission.indexOf(" %")),
                        commissionRate: item.commissionRate,
                        type: 1
                    })
                }), cb(null, obs)
            } else {
                !sign && res && res.hasOwnProperty("url") ? bgWork.get(res.url, "json", function (_sign, _res) {
                    !_sign && _res && _res.hasOwnProperty("url") && dialog.msg("阿里要喝水了,我的心也好累"), cb("访问过于频繁，请求失败")
                }) : cb("获取定向计划失败")
            }
        })
    },
    getCampaignsPlan: function getCampaignsPlan(tbtoken, cb) {
        var timestmp = Date.now();
        var turl = "https://pub.alimama.com/shopdetail/campaigns.json?oriMemberId=" + libCollect.getSellerId() + "&t=" + timestmp + "&_tb_token_=" + tbtoken + "&_input_charset=utf-8";
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res && res.ok && res.data.hasOwnProperty("campaignList") && res.data.campaignList.length > 0) {
                var obs = [],
                    a = res.data.campaignList,
                    b = res.data.exsitApplyList;
                var sid;
                a.map(function (item) {
                    var isExist = false,
                        existStatus = null,
                        existId = null;
                    var rpt = item.rptCpsShCampaign30d;
                    sid = item.shopKeeperId;
                    b && b.map(function (_item) {
                        if (_item.campaignId == item.campaignId) {
                            isExist = true, existStatus = _item.status, existId = _item.id;
                            b.splice(_item)
                        }
                    }), obs.push({
                        campaignName: item.campaignName,
                        campaignId: item.campaignId,
                        shopkeeperId: item.shopKeeperId,
                        needApply: 3 == item.properties ? "是" : "否",
                        commissionRate: -1,
                        avgCommissionRate: item.avgCommission,
                        exist: isExist,
                        existStatus: existStatus,
                        existId: existId,
                        type: item.campaignId ? "DIRECT" : "COMMON",
                        tkerNum: rpt ? rpt.ninetyPubNum : 0,
                        tk30Sales: rpt ? rpt.thirtyCmSettleNum : 0,
                        tk30Commission: rpt ? rpt.thirtyCmCommisionAmt : 0
                    })
                });
                b && b.map(function (item) {
                    obs.push({
                        campaignName: null,
                        campaignId: item.campaignId,
                        shopkeeperId: sid,
                        needApply: '是',
                        commissionRate: -1,
                        avgCommissionRate: -1,
                        exist: true,
                        existStatus: item.status,
                        existId: item.id,
                        type: "DIRECT",
                        tkerNum: 0,
                        tk30Sales: 0,
                        tk30Commission: 0
                    })
                });
                cb(null, obs)
            } else if (!sign && res && res.hasOwnProperty("url")) {
                dialog.msg("阿里要喝水了,我的心也好累")
            } else {
                sign || !res.hasOwnProperty("url") || res.hasOwnProperty("campaignList") ? cb("获取所有公开计划列表失败") : cb("访问过于频繁，请求失败", res.url)
            }
        })
    },
    getCampaignDetail: function getCampaignDetail(tbtoken, campaignid, shopkeeperid, campaignrate, cb) {
        var turl = "https://pub.alimama.com/campaign/campaignDetail.json?campaignId=" + campaignid + "&shopkeeperId=" + shopkeeperid + "&t=" + Date.now() + "&pvid=&_tb_token_=" + tbtoken + "&_input_charset=utf-8";
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res && res.data.cpsCampaignDO) {
                var item = res.data.cpsCampaignDO,
                    rpt = item.rptCpsShCampaign30d;
                cb(null, {
                    campaignName: item.campaignName,
                    campaignId: item.campaignId,
                    shopkeeperId: item.shopKeeperId,
                    needApply: 2 == item.properties ? "是" : "否",
                    commissionRate: campaignrate,
                    avgCommissionRate: item.avgCommission,
                    exist: false,
                    existStatus: null,
                    existId: null,
                    applySend: res.data.noneedapply,
                    type: item.campaignId ? "DIRECT" : "COMMON",
                    tkerNum: rpt ? rpt.ninetyPubNum : 0,
                    tk30Sales: rpt ? rpt.thirtyCmSettleNum : 0,
                    tk30Commission: rpt ? rpt.thirtyCmCommisionAmt : 0
                })
            } else cb("没有阿里计划详情")
        })
    },
    getRateFromCampaignList: function getRateFromCampaignList(gid, cid, sid, uid, tbtoken, cb) {
        ! function fn(gid, cid, sid, uid, page, total, tbtoken) {
            var timestmp = Date.now();
            var turl = "https://pub.alimama.com/campaign/merchandiseDetail.json?campaignId=" + cid + "&shopkeeperId=" + sid + "&userNumberId=" + uid + "&tab=2&omid=" + uid + "&toPage=" + page + "&perPagesize=10&t=" + timestmp + "&pvid=&_tb_token_=" + tbtoken + "&_input_charset=utf-8";
            var rateper = 0;
            bgWork.get(turl, "json", function (sign, res) {
                if (!sign && res && res.ok && res.data.hasOwnProperty("paginator") && res.data.hasOwnProperty("pagelist") && res.data.pagelist.length > 0) {
                    var obs = res.data.pagelist,
                        totalPage = res.data.paginator.lastPage,
                        limit = 20,
                        breaknum = 99;
                    totalPage = totalPage > limit ? limit : totalPage;
                    for (var i = 0; i < obs.length; i++) {
                        if (obs[i].auctionId == parseInt(gid)) {
                            rateper = obs[i].commissionRatePercent;
                            cb(rateper * 100);
                            page = breaknum;
                            break
                        }
                    }
                    if (++page <= totalPage) {
                        fn(gid, cid, sid, uid, page, totalPage, tbtoken, cb)
                    }
                    if (page == totalPage + 1 && page != breaknum) {
                        cb(0)
                    }
                }
            })
        }(gid, cid, sid, uid, 1, 1, tbtoken, cb)
    },
    getKeeper30DayRpt: function getKeeper30DayRpt(uid, tbtoken, cb) {
        var turl = "https://pub.alimama.com/shopdetail/keeper30DayRpt.json?oriMemberId=" + uid + "&t=" + Date.now() + "&pvid=&_tb_token_=" + tbtoken + "&_input_charset=utf-8";
        bgWork.get(turl, "json", function (sign, res) {
            !sign && res ? cb(null, {
                tkSales: res.data.cpsSh30data.thirtyCmSettleNum,
                totalFee: res.data.cpsSh30data.thirtyCmCommisionAmt
            }) : cb('没有店铺推广数据')
        })
    },
    getCollectDirectPlan: function getCollectDirectPlan(cb) {
        var turl = "http://open-api.shihuizhu.com/material/detail?gid=" + libCollect.getItemId();
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res && (typeof res === "undefined" ? "undefined" : _typeof(res)) == "object") {
                if (res.ratio_type === "定向") {
                    cb(null, {
                        rate: parseFloat(res.dx_ratio) * 100,
                        type: 'DIRECT',
                        cid: libCollect.getQueryString("campaignId", res.dx_url),
                        sid: libCollect.getQueryString("shopkeeperId", res.dx_url)
                    })
                } else cb("没有定向计划")
            } else cb("乐推api出现问题")
        })
    },
    getCollectDirectRate: function getCollectDirectRate(itemid, cb) {
        var turl = "http://open-api.shihuizhu.com/material/detail?gid=" + itemid;
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res && (typeof res === "undefined" ? "undefined" : _typeof(res)) == "object") {
                if (res.ratio_type === "定向") {
                    cb(null, parseFloat(res.dx_ratio) * 100)
                } else cb("没有定向计划")
            } else cb("乐推api出现问题")
        })
    },
    applyPlan: function applyPlan(cid, sid, reason, tbtoken, cb) {
        var postdata = {
            campId: cid,
            keeperid: sid,
            applyreason: reason,
            t: new Date().valueOf(),
            pvid: '',
            _tb_token_: tbtoken
        };
        bgWork.post("https://pub.alimama.com/pubauc/applyForCommonCampaign.json", urlParam(postdata), '', function (sign, res) {
            !sign && res.hasOwnProperty("info") && res.info.ok ? cb(null, res.info) : !sign && res.hasOwnProperty("info") && "您已经在申请该计划或您已经申请过该掌柜计划!!" === res.info.message ? cb(null, cb.info) : sign || !res.hasOwnProperty("url") || res.hasOwnProperty("info") ? cb("申请定向计划失败") : bgWork.get(res.url, "json", function (_sign, _res) {
                !_sign && _res && _res.hasOwnProperty("url") && dialog.msg("阿里要喝水了,我的心也好累"), cb("访问过于频繁，请求失败")
            })
        })
    },
    exitPlan: function exitPlan(cid, tbtoken, cb) {
        var postdata = {
            _tb_token_: tbtoken,
            pubCampaignid: cid
        };
        bgWork.post("https://pub.alimama.com/campaign/exitCampaign.json", postdata, "json", function (sign, res) {
            !sign && res.ok && res.hasOwnProperty("info") ? cb(null, res.info.ok) : sign || !res.hasOwnProperty("url") || res.hasOwnProperty("info") ? cb("退出计划失败") : bgWork.get(res.url, "json", function (_sign, _res) {
                !_sign && _res && _res.hasOwnProperty("url") && dialog.msg("阿里要喝水了,我的心也好累"), cb("访问过于频繁，请求失败")
            })
        })
    },
    getJutaobaoInfo: function getJutaobaoInfo(cb) {
        var turl = "https://dskip.ju.taobao.com/detail/json/item_dynamic.htm?item_id=" + libCollect.getItemId();
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res) {
                if (res.success == "true" && _typeof(res.data) == "object") {
                    if (res.data.hasOwnProperty("soldCount")) {
                        var obj = {
                            sale: parseInt(res.data.soldCount),
                            sellrate: (parseFloat(res.data.soldCount) / (parseFloat(res.data.stock) + parseFloat(res.data.soldCount)) * 100).toFixed(1)
                        };
                        cb(null, obj)
                    } else cb("还没开售")
                } else cb("没有对应的聚划算数据")
            } else cb("获取聚划算数据失败")
        })
    },
    getContentInfo: function getContentInfo(tbtoken, cb) {
        var turl = "https://pub.alimama.com/shopdetail/shopinfo.json?oriMemberId=" + libCollect.getSellerId() + "&t=" + Date.now() + "&pvid=&_tb_token_=" + tbtoken + "&_input_charset=utf-8";
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res && res.hasOwnProperty("info") > 0) {
                res.info.ok && res.data.hasOwnProperty("card") > 0 ? cb(null, res.data.card.jsonData) : cb("没有找到")
            } else if (!sign && res && res.hasOwnProperty("url") > 0) { }
        })
    },
    getShopSellerInfo: function getShopSellerInfo(cb) {
        var url = 'https://h5api.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?',
            data = {
                appKey: 12574478,
                api: 'mtop.taobao.detail.getdetail',
                v: '6.0',
                ttid: encodeURIComponent('2016@taobao_h5_2.0.0'),
                isSec: 0,
                ecode: 0,
                AntiFlood: true,
                AntiCreep: true,
                H5Request: true,
                data: encodeURIComponent("{\"exParams\":\"{\\\"id\\\":\\\"" + libCollect.getItemId() + "\\\"}\",\"itemNumId\":\"" + libCollect.getItemId() + "\"}")
            };
        url = url + urlParam(data);
        bgWork.get(url, '', function (sign, res) {
            if (!sign && res) {
                var seller = res.data.seller;
                seller ? cb(null, {
                    allItems: seller.allItemCount,
                    fans: seller.fans,
                    start: new Date(seller.starts).format("yyyy-MM-dd")
                }) : cb('出现错误')
            } else cb('出现错误')
        })
    },
    // 上传佣金
    sendrate: function sendrate(rateinfo, cb) {
        var url = 'http://zsxt.letuilm.com/api/v1/cjNewRate',
            data = {
                itemId: libCollect.getItemId(),
                rate: rateinfo
            };
        bgWork.post(url, data, '', function (sign, res) {
            if (sign.status == 200) {
                // console.log('上传佣金返回--',sign)
                cb(null, {
                    status: sign.status
                })
            } else cb('出现错误')
        })
    }
};
var getPlan = {
    brand: '<div class="dxbrand"><ul><li><div class="ifshow"><i class="icon c-7"></i>定向</div></li><li><div id="dxrate" class="rg">--%</div></li></ul></div>',
    action: function action() {
        planWork.getTbkPrivilege(function (sign, obj, coup) {
            if (!sign && obj) {
                var rate = checkNum(obj.commissionRate);
                rate == 0 && $(".title").children(".c-1").parent().html('<i class="icon c-warn"></i>商品无佣金');
                $(".info").children(".col-2").text(rate);
                console.log('佣金返回', rate)
                planWork.sendrate(rate, function (sign2, obj2) {
                    if (!sign2 && obj2) { }
                })
                $(".c-1").after("佣金<sp>" + rate + "%</sp>");
                obj.hasOwnProperty("tkObj") ? ($("#ma-0").text(obj.tkObj.tkSales),
                    $("#ma-1").text(obj.tkObj.tkCommi),
                    $("#ma-2").text(obj.tkObj.cateName)) : platformWork.getCategory(function ($sign, $text) {
                        // console.log('$sign, $text',$sign, $text)
                        !$sign && $text && $("#ma-2").text($text.category)
                    }), spreadformWork.getCategory(function ($sign, $text) {
                        !$sign && $text && $("#ma-2").text($text.category)
                        // console.log('$text', $text)
                    });
                obj.hasOwnProperty("campObj") && getPlan.showTable1(obj.campObj);
                (typeof coup === "undefined" ? "undefined" : _typeof(coup)) == "object" && platformWork.showTable1(coup), spreadformWork.showTable1(coup);
                planWork.getUnionPubContextInfo(function (_sign, _obj) {
                    !_sign && _obj && (_obj.login ? getPlan.logined(obj) : getPlan.unlogin(obj));
                    _sign && getPlan.unlogin(obj)
                })
            } else $(".title").children(".c-1").parent().html('<i class="icon c-warn"></i>商品无佣金')
        });
        planWork.getJutaobaoInfo(function (sign, obj) {
            !sign && obj ? ($("#ma-3").text(obj.sale), $("#ma-4").text(obj.sellrate + '%'), $("#juspan").attr("style", "display:block;")) : $("#juspan").attr("style", "display:none;")
        });
        planWork.getShopSellerInfo(function (sign, obj) {
            if (!sign && obj) {
                $("#ma-5").text(obj.fans);
                $("#ma-6").text(obj.allItems);
                $("#ma-7").text(obj.start)
            } else $("#shopspan").attr("style", "display:none;")
        })
    },
    unlogin: function unlogin(obj) {
        getPlan.showTableLogin();
        planWork.getCollectDirectPlan(function ($sign, $obj) {
            if (!$sign && $obj) {
                var rate1 = parseFloat(obj.commissionRate),
                    rate2 = $obj.rate / 100;
                getPlan.showTable2({
                    campaignName: '定向计划',
                    campaignId: $obj.cid,
                    shopkeeperId: $obj.sid,
                    needApply: "是",
                    commissionRate: $obj.rate,
                    avgCommissionRate: 0,
                    exist: false,
                    existStatus: null,
                    existId: null,
                    type: "DIRECT",
                    tkerNum: 0,
                    tk30Sales: 0,
                    tk30Commission: 0
                });
                if (rate1 < rate2) {
                    var $rate = checkNum(rate2);
                    $(".info").children(".col-2").text($rate);
                    $("div.title:first").before(getPlan.brand);
                    $("#dxrate").text($rate + '%');
                    $("#dxrate").width($(".c-1").parent().children("sp").width());
                    $("#noname").attr("style", "display:block;")
                }
            }
        })
    },
    logined: function logined(obj) {
        bgWork.getToken(function (sign, token) {
            if (!sign && token) {
                planWork.getContentInfo(token, function (_sign, _obj) {
                    !_sign && _obj ? aliContact = {
                        wx: _obj.微信,
                        qq: _obj.QQ,
                        wb: _obj.微博,
                        ww: _obj.旺旺
                    } : aliContact = null
                });
                if (obj.hasOwnProperty("campObj")) {
                    getPlan.step(obj, token);
                    planWork.getOptimusMaterial(token, function ($sign, $obj) {
                        if (!$sign && $obj) {
                            $obj.campObj.type == 'ZX' && getPlan.showTable1($obj.campObj)
                        }
                    })
                } else {
                    planWork.getOptimusMaterial(token, function ($sign, $obj) {
                        if (!$sign && $obj) {
                            $("#ma-0").text($obj.tkSales);
                            getPlan.step($obj, token)
                        }
                    })
                }
            }
        })
    },
    step: function step(pgk, tbToken) {
        var $campObjs = [],
            $this = getPlan;
        var commonrate = pgk.campObj.type == 'COMMON' ? pgk.campObj.rate : -1;
        pgk.campObj.type != 'COMMON' && $this.showTable1(pgk.campObj);
        planWork.getCollectDirectPlan(function (flag, element) {
            if (!flag && element) {
                planWork.getCampaignDetail(tbToken, element.cid, element.sid, element.rate, function (_flag, _element) {
                    if (!_flag && _element) {
                        planWork.getCampaignsPlan(tbToken, function (_sign, _list) {
                            if (!_sign && _list && _list.length > 0) {
                                var $rate = checkNum(_element.commissionRate) / 100;
                                $("div.title:first").before($this.brand);
                                $("#dxrate").text($rate + '%');
                                $("#noname").attr("style", "display:block;");
                                var isInside = false;
                                _list.map(function (item) {
                                    if (item.type == 'COMMON' && commonrate > 0) {
                                        item.commissionRate = commonrate
                                    }
                                    if (item.campaignId == _element.campaignId) {
                                        item.campaignName = _element.campaignName;
                                        item.commissionRate = _element.commissionRate;
                                        item.tkerNum = _element.tkerNum;
                                        item.tk30Sales = _element.tk30Sales;
                                        item.tk30Commission = _element.tk30Commission;
                                        isInside = true
                                    }
                                });
                                !isInside && _list.push(_element);
                                $this.getExcaRate(_list, tbToken, function ($list) {
                                    $list.map(function ($item) {
                                        $this.showTable2($item);
                                        $campObjs.push({
                                            id: $item.campaignId,
                                            type: $item.type,
                                            rate: parseFloat($item.commissionRate) / 100
                                        })
                                    })
                                })
                            }
                        })
                    }
                })
            } else {
                planWork.getCampaignsPlan(tbToken, function (_sign, _list) {
                    if (!_sign && _list && _list.length > 0) {
                        _list.map(function (item) {
                            if (item.type == 'COMMON' && commonrate > 0) {
                                item.commissionRate = commonrate
                            }
                        });
                        $this.getExcaRate(_list, tbToken, function ($list) {
                            $list.map(function ($item) {
                                $this.showTable2($item);
                                $campObjs.push({
                                    id: $item.campaignId,
                                    type: $item.type,
                                    rate: parseFloat($item.commissionRate) / 100
                                })
                            })
                        })
                    }
                })
            }
        });
        setTimeout(function () {
            serverWork.addDxgood({
                gid: libCollect.getItemId(),
                campObj: JSON.stringify($campObjs)
            })
        }, 10000)
    },
    showTableLogin: function showTableLogin() {
        var warring = '<tr><td colspan="6" class="center"><a class="loginwarring">登陆阿里妈妈后才能看见详细计划喔。<br>点我去登录阿里妈妈</a></td></tr>';
        $("#planheader").append(warring)
    },
    showTable1: function showTable1(item) {
        var name = '',
            type = '',
            stamp = '',
            rate = parseFloat(item.rate) / 100;
        switch (item.type) {
            case 'MKT':
                stamp = 0, type = '营销', name = '营销计划';
                break;
            case 'ZX':
                stamp = 1, type = '自选', name = '自选计划';
                break;
            case 'COMMON':
                stamp = 2, type = '通用', name = '通用计划';
                break;
            case 'DIRECT':
                stamp = 3, type = '定向', name = '定向计划';
                break
        }
        var tabtxt = "<tr><td>" + name + "</td><td>" + rate + "%</td><td><span class=\"simp-" + stamp + "\">" + type + "</span></td><td>否</td><td></td><td><a id=\"cuid-0-0\" class=\"planwork\">查看详情</a></td></tr>";
        $("#planheader").text().indexOf(name) < 0 && $("#planheader").append(tabtxt)
    },
    showTable2: function showTable2(item) {
        var cid = item.campaignId,
            uid = item.shopkeeperId ? item.shopkeeperId : "0",
            sid = item.shopkeeperId,
            eid = item.existId ? item.existId : "0",
            name = item.campaignName,
            rate = parseFloat(item.commissionRate) / 100,
            estatus = item.existStatus,
            napply = item.needApply,
            stamp = 0,
            type = '';
        switch (item.type) {
            case 'MKT':
                stamp = 0, type = '营销';
                break;
            case 'ZX':
                stamp = 1, type = '自选';
                break;
            case 'COMMON':
                stamp = 2, type = '通用';
                break;
            case 'DIRECT':
                stamp = 3, type = '定向';
                break
        }
        var passstr = getPlan.passStr(estatus, napply),
            button = cid > 2 ? getPlan.resetBtn(passstr, cid, sid, eid) : '';
        var tabtxt = "<tr><td>" + name + "</td><td id=\"cid-R-" + cid + "\">" + rate + "%</td><td><span class=\"simp-" + stamp + "\">" + type + "</span></td><td id=\"cid-P-" + cid + "\">" + passstr + "</td><td id=\"cid-B-" + cid + "\">" + button + "</td><td><a id=\"cuid-" + cid + "-" + uid + "\" class=\"planwork\">查看详情</a></td></tr>";
        $("#planheader").append(tabtxt);
        var _rate = parseFloat($(".info").children(".col-2").text());
        _rate < rate && $(".info").children(".col-2").text(rate)
    },
    getExcaRate: function getExcaRate(tlist, tbToken, pgk) {
        var n = 0,
            m = tlist.length,
            l = [],
            t = tlist;
        ! function fn(n, m, l, t) {
            var obj = t[n];
            var rate = obj.commissionRate,
                avgrate = obj.avgCommissionRate,
                gid = libCollect.getItemId(),
                cid = obj.campaignId,
                sid = obj.shopkeeperId,
                uid = libCollect.getSellerId();
            if (rate < 0) {
                planWork.getRateFromCampaignList(gid, cid, sid, uid, tbToken, function (Rate) {
                    obj.commissionRate = parseFloat(Rate || avgrate);
                    l.push(obj);
                    ++n < m ? fn(n, m, l, t, pgk) : pgk(l)
                })
            } else {
                l.push(obj);
                ++n >= m && pgk(l)
            }
        }(n, m, l, t, pgk)
    },
    passStr: function passStr(status, apply) {
        if (status) {
            var clevel = "通过";
            if (apply == "是") {
                if (status == 1) {
                    clevel = "审核中"
                } else if (status == 2) {
                    clevel = "通过"
                } else if (status == 3) {
                    clevel = "拒绝"
                }
            }
            return apply + "<span class=\"hihit\">（" + clevel + "）</span>"
        } else {
            return apply
        }
    },
    resetBtn: function resetBtn(passstr, cid, sid, eid) {
        var html = "<button class=\"special\" type=\"button\" id=\"btn-T-" + cid + "-" + sid + "\" value=\"" + cid + "-" + sid + "-" + eid + "-0\">申请计划</button>";
        if (passstr.indexOf("（通过）") > 0) {
            html = html.replace("special", "special pass").replace("申请计划", "退出计划")
        } else if (passstr.indexOf("（审核中）") > 0) {
            html = html.replace("special", "special pass").replace("申请计划", "已申请")
        }
        return html
    },
    resetTable: function resetTable() {
        bgWork.getToken(function (flag, token) {
            if (!flag && token) {
                planWork.getCampaignsPlan(token, function (sign, plist) {
                    if (!sign && plist) {
                        plist.map(function (item) {
                            var tag1 = "#cid-P-" + item.campaignId,
                                tag2 = "#cid-B-" + item.campaignId;
                            if (item.campaignId > 5) {
                                var passstr = getPlan.passStr(item.existStatus, item.needApply);
                                var cid = item.campaignId,
                                    sid = item.shopkeeperId,
                                    eid = item.existId ? item.existId : "0";
                                var btnstr = getPlan.resetBtn(passstr, cid, sid, eid);
                                $(tag1).html(passstr);
                                $(tag2).html(btnstr)
                            }
                        })
                    }
                })
            }
        })
    }
};
var couponWork = {
    nums: 0,
    getCouponCart: function getCouponCart(cb) {
        var turl = "https://cart.taobao.com/json/GetPriceVolume.do?sellerId=" + libCollect.getSellerId();
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res.hasOwnProperty("priceVolumes")) {
                var dt = res.priceVolumes;
                dt.map(function (item) {
                    item.activityId = item.id
                }), cb(null, dt)
            } else {
                var text = '<div class="cent"><button class="shopcoup">登陆淘宝查看店铺劵</button></div>';
                $("#couponheader").parent().after(text)
            }
        })
    },
    getOneCookie: function getOneCookie(cb) {
        var url = 'http://zhushou4.taokezhushou.com/api/v1/tip?version=7.0.0.1';
        bgWork.get(url, "json", function (sign, res) {
            !sign && res && res.msg === '获取成功' ? bgWork.getCookie("http://taokezhushou.com/", "COMMON_TOKEN", function (_sign, _res) {
                !_sign && _res ? cb(null, _res) : cb('出现问题')
            }) : cb('出现问题')
        })
    },
    getOtherCoupon: function getOtherCoupon(token, cb) {
        var url = 'http://hs.taokezhushou.com/v1/coupon/get?',
            param = {
                goods_id: libCollect.getItemId(),
                seller_id: libCollect.getSellerId(),
                token: token
            };
        bgWork.get(url + urlParam(param), "json", function (sign, res) {
            !sign && res ? cb(null, res) : cb('出现问题')
        })
    },
    work: function work() {
        var $this = couponWork;
        $this.getCouponCart(function (sign, coupons) {
            !sign && coupons && coupons.map(function (item) {
                var gid = libCollect.getItemId(),
                    aid = item.activityId;
                platformWork.checkCoupon2(gid, aid, function (flag, coupon) {
                    !flag && coupon && platformWork.showTable1(coupon)
                })
                spreadformWork.checkCoupon2(gid, aid, function (flag, coupon) {
                    !flag && coupon && spreadformWork.showTable1(coupon)
                })
            })
        });
        $this.getOneCookie(function (sign, commtoken) {
            !sign && commtoken && $this.getOtherCoupon(commtoken, function (symbol, record) {
                if (!symbol && record && record.status === "SUCCESS" && record.data && record.data.length > 0) {
                    record.data.map(function (coupon) {
                        var gid = libCollect.getItemId(),
                            aid = coupon.coupon_id;
                        if (aid !== "-" && platformWork.activityList.indexOf(aid) == -1) {
                            platformWork.activityList.push(aid);
                            platformWork.checkCoupon2(gid, aid, function (flag, coupon) {
                                !flag && coupon && platformWork.showTable1(coupon)
                            })
                            spreadformWork.activityList.push(aid);
                            spreadformWork.checkCoupon2(gid, aid, function (flag, coupon) {
                                !flag && coupon && spreadformWork.showTable1(coupon)
                            })
                        }
                    })
                }
            })
        })
    }
};
//推广平台
var platformWork = {
    html: "",
    activityList: [],
    action: function action() {
        couponWork.work();
        var itemid = libCollect.getItemId(),
            $this = platformWork;
        $this.getShiHuiZhuInfo(function (sign, obj) {
            // console.log('实惠猪11sign, obj', sign, obj)
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('实惠猪', null)
        });
        $this.getHaodankuInfo(function (sign, obj) {
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('好单库', null)
        });
        $this.getDataokeInfo(function (sign, obj) {
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('大淘客', null)
        });
        $this.getXuandanInfo(function (sign, obj) {
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('选单网', null)
        })
    },
    step: function step(gid, element) {
        var $this = platformWork,
            aid = element.coupon.activityId;
        if ($this.activityList.indexOf(aid) == -1) {
            $this.activityList.push(aid);
            $this.checkCoupon2(gid, aid, function (flag, coupon) {
                !flag && coupon && $this.showTable1(coupon)
            })
        }
    },
    checkCoupon2: function checkCoupon2(gid, aid, cb) {
        var data = {
            goods_id: gid,
            event_id: aid
        };
        var url = "http://tc-tz.yiquntui.com/api/getcoupon?" + urlParam(data);
        bgWork.get(url, "json", function (sign, res) {
            if (!sign && res) {
                if (_typeof(res.data.data) == "object") {
                    var dt = res.data.data,
                        sellerId = libCollect.getSellerId();
                    var activityId = dt.coupon_activity_id,
                        type = parseInt(dt.coupon_type);
                    cb(null, {
                        activityId: dt.coupon_activity_id,
                        receive: dt.coupon_total_count - dt.coupon_remain_count,
                        surplus: dt.coupon_remain_count,
                        total: dt.coupon_total_count,
                        applyAmount: dt.coupon_start_fee,
                        amount: dt.coupon_amount,
                        start: Date.parse(new Date(dt.coupon_start_time)),
                        end: Date.parse(new Date(dt.coupon_end_time)),
                        type: parseInt(dt.coupon_type),
                        url: type == 0 ? "https://market.m.taobao.com/apps/aliyx/coupon/detail.html?wh_weex=true&seller_id=" + sellerId + "&activity_id=" + activityId : type == 1 ? "https://uland.taobao.com/quan/detail?sellerId=" + sellerId + "&activityId=" + activityId : null
                    })
                } else cb('优惠卷不存在')
            } else cb('查卷接口失败')
        })
    },
    getShiHuiZhuInfo: function getShiHuiZhuInfo(cb) {
        var $this = platformWork,
            url = "http://gateway.shihuizhu.net/api/goods/" + libCollect.getItemId() + "?" + Date.now();
        bgWork.get(url, "json", function (sign, res) {
            console.log('实惠猪sign,res', sign, res)
            bgWork.get('http://shihuizhu.com/details?id=' +res.result.gid, "json", function (signs, err) {
                // console.log('sign, err', signs)

                let compon = $this.GetTagByClassUsingRegex('div', 'compon', signs.responseText)[0] // 匹配出优惠券价格
                // console.log('compon',compon)
                let compon2 = $this.GetTagByClassUsingRegex('span', '', compon, 1)[0] // 匹配出优惠券价格
                // console.log('compon2',compon2)
                let compon3 = parseFloat($this.GetTagByClassUsingRegex('span', '', compon2, 2)) // 匹配出优惠券价格
                console.log('compon3', compon3)

                let time = $this.GetTagByClassUsingRegex('p', '', compon, 1)[0] // 匹配出有效时间
                let time2 = $this.GetTagByClassUsingRegex('span', '', time, 1)[1] // 匹配出有效时间
                let time3 = $this.GetTagByClassUsingRegex('span', '', time2, 2) // 匹配出有效时间
                let time4 = time3.slice(10, time3.length)
                let time5 = time3.slice(5, time3.length)
                console.log('time4', time4)

                $this.contractorWork(res.result.uid);
                var $start = new Date(res.result.coupon_start_time).valueOf(),
                    $end = new Date(time5).valueOf(),
                    $now = new Date(new Date().setHours(0, 0, 0, 0)).getTime(),
                    $username = res.result.username;
                console.log('$now', $now, 'end', $end)
                if ($end > $now || $end === $now || $end == 0) {
                    cb(null, {
                        name: '实惠猪',
                        desc: res.result.intro_foot,
                        intro: res.result.intro,
                        pic: res.result.long_pic == "" ? res.result.long_pic : res.result.long_pic.indexOf("http") > -1 ? res.result.long_pic : "http:" + res.result.long_pic,
                        rebate: parseFloat(res.result.price),
                        coupon: {
                            activityId: libCollect.getCouponId(res.result.coupon_url),
                            start: $start,
                            end: $end,
                            amount: parseFloat(res.result.coupon_money)
                        },
                        tkCoInfo: {
                            name: !isEmpty($username) && $username != 'null' ? $username : '我要担保',
                            url: "http://www.shihuizhu.com/details/?id=" + res.result.id,
                            content: "http://www.shihuizhu.com/person/" + res.result.uid
                        }
                    })
                } else {

                    $this.contractorWork(0),
                        cb('实惠猪过期')
                }
            })
        })
    },
    getHaodankuInfo: function getHaodankuInfo(cb) {
        bgWork.get("https://www.haodanku.com/indexapi/get_allitem_list?keyword=" + libCollect.getItemId() + "&p=1", "json", function (sign, res) {
            // console.log('好单库sign,res',sign, res)    
            if (!sign && res && res.hasOwnProperty("item_info")) {
                if (res.item_info.length > 0) {
                    var dt = res.item_info[0];
                    bgWork.get("https://www.haodanku.com/detail/item_info?id=" + dt.id, "json", function (_sign, _res) {
                        if (!_sign && _res) {
                            var _dt = _res.data;
                            cb(null, {
                                name: '好单库',
                                desc: _dt.itemdesc,
                                pic: "http://img.haodanku.com/" + _dt.itempic_copy,
                                rebate: parseFloat(_dt.itemendprice),
                                coupon: {
                                    activityId: _dt.activityid,
                                    start: parseInt(_dt.couponstarttime) * 1000,
                                    end: parseInt(_dt.couponendtime) * 1000,
                                    amount: parseFloat(_dt.couponmoney)
                                },
                                tkCoInfo: {
                                    name: dt.seller_name,
                                    url: "https://www.haodanku.com/Item/details?id=" + dt.id,
                                    content: "https://www.haodanku.com/Bestseller/individual?id=" + dt.seller_id
                                }
                            })
                        } else cb('好单库查询出现问题')
                    })
                } else cb("没有好单库ID")
            } else cb("好单库查询出现问题")
        })
    },
    getDataokeInfo: function getDataokeInfo(cb) {
        var data = {
            appKey: '5dfb82de06b7f',
            appSecret: 'fb702d6038659eb4ab3b4872e66a34c0',
            version: 'v2.1.2',
            pageId: 1,
            pageSize: 100,
            keyWords: libCollect.getSimpeLink(window.location.href)
        };
        var _urlparam = urlParam(data);
        var _urlsign = MD5(_urlparam + "&key=" + data.appSecret);
        var turl = "https://openapi.dataoke.com/api/goods/get-dtk-search-goods?" + _urlparam + "&sign=" + _urlsign;
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res) {
                if (res.code == 0 && res.data.list.length > 0) {
                    var dt = res.data.list[0];
                    cb(null, {
                        name: '大淘客',
                        desc: dt.desc,
                        pic: dt.marketingMainPic,
                        rebate: dt.actualPrice,
                        coupon: {
                            activityId: libCollect.getCouponId(dt.couponLink),
                            start: Date.parse(new Date(dt.couponStartTime)),
                            end: Date.parse(new Date(dt.couponEndTime)),
                            amount: parseFloat(dt.couponPrice)
                        },
                        tkCoInfo: {
                            name: dt.teamName,
                            url: "http://www.dataoke.com/item?id=" + dt.id,
                            content: ''
                        }
                    })
                } else cb("大淘客平台：" + res.msg)
            } else cb("大淘客查询出现问题")
        })
    },
    getXuandanInfo: function getXuandanInfo(cb) {
        var url = 'http://api.xuandan.com/DataApi/Checkitem?appkey=utfic1soaj&id=' + libCollect.getItemId();
        bgWork.get(url, "json", function (sign, res) {
            if (!sign && res) {
                if (res.error == 0 && res.msg == '在线') {
                    var dt = res.data[0];
                    cb(null, {
                        name: '选单网',
                        desc: '',
                        pic: '',
                        rebate: dt.LastPrice,
                        coupon: {
                            activityId: libCollect.getCouponId(dt.ActLink),
                            start: Date.parse(new Date(dt.BeginDate)),
                            end: Date.parse(new Date(dt.EndDate)),
                            amount: 0
                        },
                        tkCoInfo: {
                            name: dt.TeamName,
                            url: "http://www.xuandan.com/Detail.html?id=" + dt.ID,
                            content: ''
                        }
                    })
                } else cb('选单网没有这个商品')
            } else cb('选单网出现问题')
        })
    },
    getCategory: function getCategory(cb) {
        var cateid = '',
            userid = libCollect.getSellerId(),
            goodid = libCollect.getItemId();
        $('script').each(function () {
            var cid = libCollect.getCategoryId(this.text);
            if (null != cid) cateid = cid
        });
        var turl = "http://plugin.qly360.com/productDetailList_UC.do?spid=" + goodid + "&userid=" + userid + "&category=-&cate=" + cateid + "&delist=-";
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res) {
                var obt = {
                    category: res[0].category,
                    unshelve: res[0].delist
                };
                cb(null, obt)
            } else cb("没有数据")
        })
    },
    getCategory2: function getCategory2(cb) {
        var data = {
            apikey: 'cE7DPwdtVEfvvqNok6JJZXmVCvGzxA2A',
            num_iids: libCollect.getItemId()
        };
        var url = "http://api.tbk.dingdanxia.com/tbk/item_info?";
        bgWork.get(url + urlParam(data), "json", function (sign, res) {
            if (!sign && res) {
                var dt = res.data[0];
                cb(null, dt.cat_name + "->" + dt.cat_leaf_name)
            } else cb("订单侠接口出现问题")
        })
    },
    getTKeasyInterface: function getTKeasyInterface(cb) {
        var gid = libCollect.getItemId(),
            sid = libCollect.getSellerId();
        var url = "https://www.tkeasy.com/interface/ItemTuiRecord?itemid=" + gid + "&sellerid=" + sid;
        bgWork.get(url, "json", function (sign, res) {
            cb(!sign && res && res.ok ? 1 : 0)
        })
    },
    trendBox: function trendBox() {
        var gid = libCollect.getItemId();
        platformWork.getTKeasyInterface(function (symbol) {
            if (symbol) {
                dialog.iframe({
                    title: '销量与传播记录',
                    width: '600px',
                    length: '90%',
                    url: "https://www.tkeasy.com/item/" + gid
                })
            } else dialog.msg('该商品没有任何联盟群传播记录')
        })
    },
    docWork: function docWork(intro, pic) {
        if (intro != "") {
            var reg = /http(s)?:\/\/img.alicdn.com\/.*?.jpg/;
            var _intro = pic != "" ? intro.replace(reg, pic) : intro;
            var tHtml = "<li id=\"docTag\" class=\"lt_column\"><div class=\"title\"><i class=\"icon doc\"></i>文案<div class=\"tooltiptext\"><span class=\"layui-layer-content\">" + _intro + "</span></div></div></li>";
            $(".tagbar").append(tHtml)
        }
    },
    showTable1: function showTable1(item) {
        var _title = item.title ? item.title : "满" + checkNum(item.applyAmount) + "减" + checkNum(item.amount),
            _time = new Date(item.start).format("MM.dd") + "-" + new Date(item.end).format("MM.dd"),
            _taken = item.receive + "/" + item.total,
            _copyurl = item.url,
            _aid = item.activityId ? item.activityId : 0,
            _type = item.type,
            tabtxt = '';
        switch (item.type) {
            case 0:
                tabtxt = "<tr><td id=\"coupname\">" + _title + "<div class=\"tip\">ID_" + _aid + "</div></td><td>店铺劵</td><td>" + _time + "</td><td>" + _taken + "</td><td><a class=\"" + (_copyurl ? "couponurl" : "") + "\" data-clipboard-text=\"" + _copyurl + "\">点击复制</a></td><td><a class=\"couponwork\" id=\"aid-" + _aid + "-" + _type + "\">点击领劵</a></td></tr>";
                break;
            case 1:
                tabtxt = "<tr><td id=\"coupname\">" + _title + "<span class=\"coup orger\">阿</span><div class=\"tip\">ID_" + _aid + "</div></td><td><span class=\"simp-0\">单品券</span></td><td>" + _time + "</td><td>" + _taken + "</td><td><a class=\"" + (_copyurl ? "couponurl" : "") + "\" data-clipboard-text=\"" + _copyurl + "\">点击复制</a></td><td><a class=\"couponwork\" id=\"aid-" + _aid + "-" + _type + "\">点击领劵</a></td></tr>";
                break;
            case 3:
                tabtxt = "<tr><td>" + _title + "<span class=\"coup blue\">阿</span></td><td><span class=\"simp-2\">阿里劵</span></td><td>" + _time + "</td><td>" + _taken + "</td><td>-</td><td><a class=\"couponwork\" id=\"aid-" + _aid + "-" + _type + "\">点击领劵</a></td></tr>";
                break
        }
        $("#couponheader").append(tabtxt);
        couponWork.nums++
    },
    showTable2: function showTable2(title, item) {
        // console.log('实惠猪11title, item',title, item)
        var link, type, tabtxt;
        switch (title) {
            case '实惠猪':
                link = 'http://www.shihuizhu.com/auth/login', type = 1;
                break;
            case '好单库':
                link = 'https://publish.haodanku.com/index/proving.html', type = 2;
                break;
            case '大淘客':
                link = 'http://www.dataoke.com/login', type = 3;
                break;
            case '选单网':
                link = 'http://fd.xuandan.com/NewManage/AddGoods', type = 4;
                break
        }
        if (item == null) {
            tabtxt = "<div><div class=\"col-1\"><i class=\"icon i-" + type + "\"></i> " + title + " </div><div class=\"col-2\"><div class=\"cell-2\"><a href=\"" + link + "\" target=\"_blank\" class=\"special\">去放单</a></a></div></div></div>"
        } else {
            var price = item.rebate,
                coupon = item.coupon.amount == 0 ? '-' : item.coupon.amount,
                time = new Date(item.coupon.end).format("MM-dd"),
                url = item.tkCoInfo.url,
                name = item.tkCoInfo.name,
                aclass = '';
            if (name == '我要担保') aclass = 'special';
            tabtxt = "<li><div><div class=\"col-1\"><i class=\"icon i-" + type + "\"></i> " + title + " </div><div class=\"col-3\"><div class=\"cell-1\"> " + price + "元 </a></div><div class=\"cell-2\"> 券 " + coupon + "元 </a></div><div class=\"cell-3\"> " + time + " </a> 到期 </div><div class=\"cell-4\"><a href=\"" + url + "\" target=\"_blank\" class=\"" + aclass + "\"> " + name + " </a></div></div></div></li>"
        }
        $("#lt_plat-" + type).html(tabtxt)
    },
    getShiHuiZhuRank: function getShiHuiZhuRank(cb) {
        var timestamp = parseInt(new Date().valueOf() / 1000);
        var url = 'http://api-test.shihuizhu.com/home.rank/salesNum?',
            data = {
                min_price: '',
                max_price: '',
                order: '',
                coupon_money: '',
                ratio: '',
                final_sales: '',
                cate: '',
                page: 1,
                limit: 60,
                keywords: '',
                type: 'hour',
                shop_name: '',
                is_chaoshi: 0,
                is_douyin: 0,
                hk: 0,
                is_dx: 0,
                is_wechat: 0,
                time: timestamp
            };
        var strParam = urlParam(data);
        var sign = MD5(strParam + '&key=shihuizhubangbang123');
        url = url + urlParam(data) + '&sign=' + sign;
        bgWork.get(url, 'json', function (s, n) {
            if (!s && n) {
                if (n.code == 0 && Array.isArray(n.data.data)) {
                    var list = [];
                    n.data.data.map(function (dt) {
                        list.push({
                            id: dt.id,
                            title: dt.sub_title,
                            img: dt.thumb,
                            link: dt.url,
                            sales: dt.lately_sales,
                            rebate: dt.price,
                            ratiotype: dt.ratio_type,
                            couponleft: dt.coupon_left,
                            coupontotal: dt.coupon_total,
                            couponmoney: dt.coupon_money,
                            comments: dt.comments,
                            tkynums: dt.tky_nums,
                            saleall: dt.final_sales,
                            shopname: dt.shop_name,
                            username: dt.username,
                            hasDoc: dt.is_delicacy == 1 ? 1 : 0,
                            istmall: dt.url.indexOf('taobao.com') > 0 ? 0 : 1,
                            rate: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? dt.dx_ratio : dt.ratio,
                            hasdx: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? 1 : 0
                        })
                    });
                    cb(null, list)
                } else cb('没有数据')
            } else cb('没有数据')
        })
    },
    showRanks: function showRanks() {
        var $this = platformWork;
        $this.getShiHuiZhuRank(function (sign, list) {
            if (!sign && Array.isArray(list)) {
                var index = 0;
                list.map(function (item) {
                    var link = "http://www.shihuizhu.com/details?id=" + item.id,
                        salenum = item.saleall,
                        commnum = item.comments;
                    if (salenum >= 10000) {
                        salenum = Math.floor(salenum / 1000) / 10 + '万'
                    }
                    if (commnum >= 10000) {
                        commnum = Math.floor(commnum / 1000) / 10 + '万'
                    }
                    var boxtxt = "\n                        <div class=\"card-box\" id=\"card-rank2-" + index + "\">\n                            <div class=\"card-img\">\n                                <a target=\"_blank\" href=\"" + link + "\">\n                                    <span class=\"card-label\">" + (index + 1) + "</span>    \n                                    " + (item.hasDoc ? '<span class="card-doc">精编文案</span>' : '') + "  \n                                    <img class=\"\" src=\"" + item.img + "\"> </a>\n                            </div>\n                            <div class=\"card-text\"><i class=\"" + (item.istmall ? 'tm' : 'tb') + "\"></i>\n                                <p class=\"card-name\" title=\"" + item.title + "\">" + item.title + "</p>\n                                <p class=\"card-sales\">近2小时销售<span>" + item.sales + "</span>件</p>\n                            </div>\n                            <div class=\"card-arae\">\n                                <ul>\n                                    <li class=\"ifshow\"> <span class=\"above\">￥" + item.rebate + "</span> <span class=\"under\">券后价</span> </li>\n                                    <li class=\"rg\"> <span class=\"above\">" + item.rate + "%</span> <span class=\"under\">" + item.ratiotype + "</span> </li>\n                                </ul>\n                            </div>\n                            <div class=\"card-line\">\n                                <p class=\"card-info\">券<span class=\"bet\">￥" + item.couponmoney + "</span>月销<span class=\"bet\">" + salenum + "</span>\n                                </p>\n                                <i class=\"more-icon\" id=\"more-rank2-" + index + "\"></i>\n                            </div>\n                            <div class=\"card-cbox\">\n                                <p class=\"item-info\">余券量<span class=\"bet\">" + item.couponleft + "/" + item.coupontotal + "</span></p>\n                                <p class=\"item-info\">评价<span class=\"bet\">" + commnum + "</span></p>\n                                <p class=\"item-info\">联盟<span class=\"bet\">" + item.tkynums + "</span></p>\n                                <p class=\"item-info\">店铺<span class=\"bet\">" + item.shopname + "</span></p>\n                                <p class=\"item-info\">放单人<span class=\"bet\">" + item.username + "</span></p>\n                            </div>\n                        </div>";
                    $(".ltrank2").append(boxtxt);
                    index++
                });
                $("i.more-icon").mouseenter(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank2') {
                        var tname = 'card-' + tidss[1] + '-' + tidss[2];
                        $("#" + tname).css("height", "374px")
                    }
                });
                $(".card-box").mouseleave(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank2') {
                        var h = $(this).height();
                        h != 292 && $(this).css("height", "274px")
                    }
                });
                $(".ltrank2").next().removeClass("pluginclear")
            }
        })
    },
    getShiHuiZhuPos: function getShiHuiZhuPos(cb) {
        var url = 'http://api-test.shihuizhu.com/home.rank/getRank?gid=' + libCollect.getItemId();
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取用户信息失败')
        })
    },
    getShiHuiZhuUser: function getShiHuiZhuUser(uid, cb) {
        var url = 'http://api-test.shihuizhu.com/home.member/profile?uid=' + uid;
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取用户信息失败')
        })
    },
    getShiHuiZhuUserGoods: function getShiHuiZhuUserGoods(uid, cb) {
        var timestamp = parseInt(new Date().valueOf() / 1000);
        var url = 'http://api-test.shihuizhu.com/home.goods/goodsList?',
            data = {
                uid: uid,
                time: timestamp
            };
        var strParam = urlParam(data);
        var sign = MD5(strParam + '&key=shihuizhubangbang123');
        url = url + urlParam(data) + '&sign=' + sign;
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取用户信息失败')
        })
    },
    getGoodDaySale: function getGoodDaySale(cb) {
        var url = 'http://api-test.shihuizhu.com/home.sales/todaySales?gid=' + libCollect.getItemId();
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取今日销量失败')
        })
    },
    contractorWork: function contractorWork(uid) {
        var isexpire = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
        var $this = platformWork
    },
    showTodaySale: function showTodaySale(sales) {
        var $this = platformWork,
            $that = historyWork,
            $chart = echarts.init(document.getElementById("todaychart")),
            $option = $that.initOption(),
            xdata = [],
            ydata = [];
        sales && Array.isArray(sales) && sales.map(function (item) {
            xdata.push(new Date(item.add_time * 1000).format("hh:ss"));
            ydata.push(item.sales_volume)
        });
        $option = $that.setOption($option, {
            x: xdata,
            y: ydata,
            text: '销量'
        });
        $chart.setOption($option)
    },
    showUserGoods: function showUserGoods(uid) {
        var $this = platformWork;
        $this.getShiHuiZhuUserGoods(uid, function (sign, res) {
            if (!sign && res && res.hasOwnProperty("page_data") > 0 && Array.isArray(res.page_data)) {
                var list = [];
                res.page_data.map(function (dt) {
                    list.push({
                        id: dt.id,
                        title: dt.sub_title,
                        img: dt.thumb,
                        link: dt.url,
                        sales: dt.today_sales,
                        rebate: dt.price,
                        ratiotype: dt.ratio_type,
                        couponleft: dt.coupon_left,
                        coupontotal: dt.coupon_total,
                        couponmoney: dt.coupon_money,
                        comments: dt.comments,
                        tkynums: dt.tky_nums,
                        saleall: dt.final_sales,
                        shopname: dt.shop_name,
                        username: dt.username,
                        hasDoc: dt.is_delicacy == 1 ? 1 : 0,
                        istmall: dt.url.indexOf('taobao.com') > 0 ? 0 : 1,
                        rate: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? dt.dx_ratio : dt.ratio,
                        hasdx: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? 1 : 0
                    })
                });
                var index = 0;
                list.map(function (item) {
                    var link = "http://www.shihuizhu.com/details?id=" + item.id,
                        salenum = item.saleall,
                        commnum = item.comments;
                    if (salenum >= 10000) salenum = Math.floor(salenum / 1000) / 10 + '万';
                    if (commnum >= 10000) commnum = Math.floor(commnum / 1000) / 10 + '万';
                    var boxtxt = "\n                            <div class=\"card-box\" id=\"card-rank1-" + index + "\">\n                                <div class=\"card-img\">\n                                    <a target=\"_blank\" href=\"" + link + "\">   \n                                        " + (item.hasDoc ? '<span class="card-doc">精编文案</span>' : '') + "  \n                                        <img class=\"\" src=\"" + item.img + "\">\n                                    </a>\n                                </div>\n                                <div class=\"card-text\"> <i class=\"" + (item.istmall ? 'tm' : 'tb') + "\"></i>\n                                    <p class=\"card-name\" title=\"" + item.title + "\">" + item.title + "</p>\n                                    <p class=\"card-sales\">今日销售<span>" + item.sales + "</span>件</p>\n                                </div>\n                                <div class=\"card-arae\">\n                                    <ul>\n                                        <li class=\"ifshow\"> <span class=\"above\">￥" + item.rebate + "</span> <span class=\"under\">券后价</span> </li>\n                                        <li class=\"rg\"> <span class=\"above\">" + item.rate + "%</span> <span class=\"under\">" + item.ratiotype + "</span> </li>\n                                    </ul>\n                                </div>\n                                <div class=\"card-line\">\n                                    <p class=\"card-info\">券<span class=\"bet\">￥" + item.couponmoney + "</span>月销<span class=\"bet\">" + salenum + "</span>\n                                    </p>\n                                    <i class=\"more-icon\" id=\"more-rank1-" + index + "\"></i>\n                                </div>\n                                <div class=\"card-cbox\">\n                                    <p class=\"item-info\">余券量<span class=\"bet\">" + item.couponleft + "/" + item.coupontotal + "</span></p>\n                                    <p class=\"item-info\">评价<span class=\"bet\">" + commnum + "</span></p>\n                                    <p class=\"item-info\">联盟<span class=\"bet\">" + item.tkynums + "</span></p>\n                                    <p class=\"item-info\">店铺<span class=\"bet\">" + item.shopname + "</span></p>\n                                    <p class=\"item-info\">放单人<span class=\"bet\">" + item.username + "</span></p>\n                                </div>\n                            </div>";
                    $(".rank1").append(boxtxt);
                    index++
                });
                $("i.more-icon").mouseenter(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank1') {
                        var tname = 'card-' + tidss[1] + '-' + tidss[2];
                        $("#" + tname).css("height", "374px")
                    }
                });
                $(".card-box").mouseleave(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank1') {
                        var h = $(this).height();
                        h != 292 && $(this).css("height", "274px")
                    }
                })
            }
        })
    },
    showContractor: function showContractor(uid, sales, user, pos) {
        var sales2h = 0,
            salesday = 0,
            catestr = '',
            direstr = '',
            posday = '-',
            posnow = '-';
        if (sales && sales.length > 0) {
            salesday = sales[sales.length - 1].sales_volume - sales[0].sales_volume;
            var time2h = new Date().valueOf() / 1000 - 2 * 60 * 60;
            var _saleitem = sales.find(function (item) {
                return item.add_time - time2h >= 0
            });
            if (_saleitem) {
                sales2h = sales[sales.length - 1].sales_volume - _saleitem.sales_volume
            }
        }
        var text = user ? "此商品由" + user.team_name + "团队担保，请放心推广" : '此商品暂无担保人，请谨慎推广！';
        var sign = user ? 'covenant' : 'warring';
        if (user && user.cate && user.cate != "") {
            catestr = user.cate.replace(/,/g, '</span><span>');
            catestr = '<span>' + catestr + '</span>'
        }
        if (user) {
            if (user.phone != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire phone\"></i>" + user.phone + "</div>"
            }
            if (user.team_qq != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire qq\"></i>" + user.team_qq + "</div>"
            }
            if (user.team_wechat != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire wechat\"></i>" + user.team_wechat + "</div>"
            }
            if (user.team_dingtalk != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire dingding\"></i>" + user.team_dingtalk + "</div>"
            }
        }
        if (pos) {
            posday = pos.today_rank == 0 ? '-' : pos.today_rank;
            posnow = pos.lately_rank == 0 ? '-' : pos.lately_rank
        }
        var brandHtml = "<div class=\"LTcontact\">\n                <div class=\"left\">\n                    <div class=\"title\"><i class=\"icon logo\"></i>乐推指数\n                    <span>全网排名<sp>No." + posday + "</sp>实时排名<sp>No." + posnow + "</sp>\n                    </span></div>\n                    <div class=\"line\">\n                        <div id=\"\" class=\"ban\">近2小时销量\n                            <sp>" + sales2h + "</sp>\n                        </div>\n                        <div class=\"ban\">全天销量\n                            <sp>" + salesday + "</sp>\n                        </div>\n                        <div id=\"todaychart\" class=\"panel p-1\"></div>\n                    </div>\n                </div>\n                <div class=\"right\"><i class=\"icon " + sign + "\"></i>\n                    <div class=\"text\">" + text + "</div>\n                </div>\n            </div>";
        $("div.tb-detail-hd").length > 0 ? $("div.tb-detail-hd").before(brandHtml) : $("div.tb-title").before(brandHtml);
        if (user) {
            var panelHtml = "<div class=\"panel p-3\"> \n                    <img class=\"avatar\" src=\"" + user.user_img + "\">\n                    <div class=\"person\">\n                        <div class=\"name\">" + user.team_name + "</div>\n                        <div class=\"locat\"> <i class=\"icon map\"></i>" + (user.area == '_' ? '中国' : user.area) + "</div>\n                        <div class=\"item\">\n                            <div class=\"item_left\">团队介绍：</div>\n                            <div class=\"item_right\">" + user.team_desc + "</div>\n                        </div>\n                        <div class=\"item\">\n                            <div class=\"item_left\">擅长领域：</div>\n                            <div class=\"item_right\">" + catestr + "</div>\n                        </div>\n                        <div class=\"item\">\n                            <div class=\"item_left\">联系方式：</div>\n                            <div class=\"item_right\">" + direstr + "</div>\n                        </div>\n                        <div class=\"point\">推广中如遇售后/定向等问题可联系该团队，联系备注乐推！</div>\n                    </div>\n                    <div class=\"mailme\">TA的商品</div>\n                    <div class=\"rank1 cab\"></div>\n                </div>";
            $("i.covenant").parent().append(panelHtml)
        } else {
            var link = 'http://www.shihuizhu.com/details?id=' + libCollect.getItemId();
            var _panelHtml = "<div class=\"panel p-2\">\n                    <a class=\"sponsor\" href=\"" + link + "\" target=\"_blank\">\n                    <img src=\"http://cdn.shihuizhu.net/img/guarantee_bg_v1.db2a749.png\">\n                        我要担保\n                    </a>\n                </div>";
            $("i.warring").parent().append(_panelHtml)
        }
        $("div.text").mouseenter(function () {
            $(this).parent().children(".panel").addClass("show")
        });
        $("div.line").mouseenter(function () {
            $(this).children(".panel").addClass("show")
        });
        $("div.panel").mouseleave(function () {
            $(this).removeClass("show")
        });
        sales && sales.length > 0 && platformWork.showTodaySale(sales);
        platformWork.showUserGoods(uid)
    },
    GetTagByClassUsingRegex: function GetTagByClassUsingRegex(tag, cls, html, num) {
        let str = html
        var reg = new RegExp("<" + tag + "[^>]*class[\\s]?=[\\s]?['\"]" + cls + "[^'\"]*['\"][\\s\\S]*?<\/" + tag + ">", "g");
        var reg2 = new RegExp("<" + tag + "[^>](.*?)<\/" + tag + ">", "g")
        if (num === 1) {
            return str.match(reg2) //返回指定的 tag
        }
        if (num === 2) {
            var result = str.replace(/<[^>]+>/g, "")
            return result
        }
        // if(num === 3){
        //     var result = str.replace(/<[^>]+>/g,"")
        //     return result
        // }
        // return html.replace(reg, '') //删除指定类名的 tag
        return str.match(reg) //返回指定类名的 tag
    }
};
var spreadformWork = {
    html: "",
    activityList: [],
    action: function action() {
        couponWork.work();
        var itemid = libCollect.getItemId(),
            $this = spreadformWork;
        $this.getShiHuiZhuInfo(function (sign, obj) {
            console.log('实惠猪00sign, obj', sign, obj)
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('实惠猪', null)
        });
        $this.getHaodankuInfo(function (sign, obj) {
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('好单库', null)
        });
        $this.getDataokeInfo(function (sign, obj) {
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('大淘客', null)
        });
        $this.getXuandanInfo(function (sign, obj) {
            if (!sign && obj) {
                $this.step(itemid, obj);
                $this.showTable2(obj.name, obj)
            } else $this.showTable2('选单网', null)
        })
    },
    step: function step(gid, element) {
        var $this = spreadformWork,
            aid = element.coupon.activityId;
        if ($this.activityList.indexOf(aid) == -1) {
            $this.activityList.push(aid);
            $this.checkCoupon2(gid, aid, function (flag, coupon) {
                !flag && coupon && $this.showTable1(coupon)
            })
        }
    },
    checkCoupon2: function checkCoupon2(gid, aid, cb) {
        var data = {
            goods_id: gid,
            event_id: aid
        };
        var url = "http://tc-tz.yiquntui.com/api/getcoupon?" + urlParam(data);
        bgWork.get(url, "json", function (sign, res) {
            if (!sign && res) {
                if (_typeof(res.data.data) == "object") {
                    var dt = res.data.data,
                        sellerId = libCollect.getSellerId();
                    var activityId = dt.coupon_activity_id,
                        type = parseInt(dt.coupon_type);
                    cb(null, {
                        activityId: dt.coupon_activity_id,
                        receive: dt.coupon_total_count - dt.coupon_remain_count,
                        surplus: dt.coupon_remain_count,
                        total: dt.coupon_total_count,
                        applyAmount: dt.coupon_start_fee,
                        amount: dt.coupon_amount,
                        start: Date.parse(new Date(dt.coupon_start_time)),
                        end: Date.parse(new Date(dt.coupon_end_time)),
                        type: parseInt(dt.coupon_type),
                        url: type == 0 ? "https://market.m.taobao.com/apps/aliyx/coupon/detail.html?wh_weex=true&seller_id=" + sellerId + "&activity_id=" + activityId : type == 1 ? "https://uland.taobao.com/quan/detail?sellerId=" + sellerId + "&activityId=" + activityId : null
                    })
                } else cb('优惠卷不存在')
            } else cb('查卷接口失败')
        })
    },
    getShiHuiZhuInfo: function getShiHuiZhuInfo(cb) {
        var $this = platformWork,
            url = "http://gateway.shihuizhu.net/api/goods/" + libCollect.getItemId() + "?" + Date.now();
        bgWork.get(url, "json", function (sign, res) {
            console.log('实惠猪sign,res', sign, res)
            bgWork.get('http://shihuizhu.com/details?id=' +res.result.gid, "json", function (signs, err) {
                // console.log('sign, err', signs)

                let compon = $this.GetTagByClassUsingRegex('div', 'compon', signs.responseText)[0] // 匹配出优惠券价格
                // console.log('compon',compon)
                let compon2 = $this.GetTagByClassUsingRegex('span', '', compon, 1)[0] // 匹配出优惠券价格
                // console.log('compon2',compon2)
                let compon3 = parseFloat($this.GetTagByClassUsingRegex('span', '', compon2, 2)) // 匹配出优惠券价格
                console.log('compon3', compon3)

                let time = $this.GetTagByClassUsingRegex('p', '', compon, 1)[0] // 匹配出有效时间
                let time2 = $this.GetTagByClassUsingRegex('span', '', time, 1)[1] // 匹配出有效时间
                let time3 = $this.GetTagByClassUsingRegex('span', '', time2, 2) // 匹配出有效时间
                let time4 = time3.slice(10, time3.length)
                let time5 = time3.slice(5, time3.length)
                console.log('time4', time4)

                $this.contractorWork(res.result.uid);
                var $start = new Date(res.result.coupon_start_time).valueOf(),
                    $end = new Date(time5).valueOf(),
                    $now = new Date(new Date().setHours(0, 0, 0, 0)).getTime(),
                    $username = res.result.username;
                console.log('$now', $now, 'end', $end)
                if ($end > $now || $end === $now || $end == 0) {
                    cb(null, {
                        name: '实惠猪',
                        desc: res.result.intro_foot,
                        intro: res.result.intro,
                        pic: res.result.long_pic == "" ? res.result.long_pic : res.result.long_pic.indexOf("http") > -1 ? res.result.long_pic : "http:" + res.result.long_pic,
                        rebate: parseFloat(res.result.price),
                        coupon: {
                            activityId: libCollect.getCouponId(res.result.coupon_url),
                            start: $start,
                            end: $end,
                            amount: parseFloat(res.result.coupon_money)
                        },
                        tkCoInfo: {
                            name: !isEmpty($username) && $username != 'null' ? $username : '我要担保',
                            url: "http://www.shihuizhu.com/details/?id=" + res.result.id,
                            content: "http://www.shihuizhu.com/person/" + res.result.uid
                        }
                    })
                } else {

                    $this.contractorWork(0),
                        cb('实惠猪过期')
                }
            })
        })
    },
    getHaodankuInfo: function getHaodankuInfo(cb) {
        bgWork.get("https://www.haodanku.com/indexapi/get_allitem_list?keyword=" + libCollect.getItemId() + "&p=1", "json", function (sign, res) {
            //  console.log('好单库',sign, res)
            if (!sign && res && res.hasOwnProperty("item_info")) {
                if (res.item_info.length > 0) {
                    couponurls = res.item_info[0].couponurl;
                    // console.log('好单库url',couponurls)
                }
                if (res.item_info.length > 0) {
                    var dt = res.item_info[0];
                    bgWork.get("https://www.haodanku.com/detail/item_info?id=" + dt.id, "json", function (_sign, _res) {
                        if (!_sign && _res) {
                            var _dt = _res.data;
                            cb(null, {
                                name: '好单库',
                                desc: _dt.itemdesc,
                                pic: "http://img.haodanku.com/" + _dt.itempic_copy,
                                rebate: parseFloat(_dt.itemendprice),
                                coupon: {
                                    activityId: _dt.activityid,
                                    start: parseInt(_dt.couponstarttime) * 1000,
                                    end: parseInt(_dt.couponendtime) * 1000,
                                    amount: parseFloat(_dt.couponmoney)
                                },
                                tkCoInfo: {
                                    name: dt.seller_name,
                                    url: "https://www.haodanku.com/Item/details?id=" + dt.id,
                                    content: "https://www.haodanku.com/Bestseller/individual?id=" + dt.seller_id
                                }
                            })
                        } else cb('好单库查询出现问题')
                    })
                } else cb("没有好单库ID")
            } else cb("好单库查询出现问题")
        })
    },
    getDataokeInfo: function getDataokeInfo(cb) {
        var data = {
            appKey: '5dfb82de06b7f',
            appSecret: 'fb702d6038659eb4ab3b4872e66a34c0',
            version: 'v2.1.2',
            pageId: 1,
            pageSize: 100,
            keyWords: libCollect.getSimpeLink(window.location.href)
        };
        var _urlparam = urlParam(data);
        var _urlsign = MD5(_urlparam + "&key=" + data.appSecret);
        var turl = "https://openapi.dataoke.com/api/goods/get-dtk-search-goods?" + _urlparam + "&sign=" + _urlsign;
        bgWork.get(turl, "json", function (sign, res) {
            //  console.log('大淘客',sign, res)
            if (!sign && res) {
                if (res.code == 0 && res.data.list.length > 0) {
                    if (res.data.list[0].couponLink) {
                        couponurls = res.data.list[0].couponLink
                        // console.log('大淘客',couponurls)
                    }
                    var dt = res.data.list[0];
                    cb(null, {
                        name: '大淘客',
                        desc: dt.desc,
                        pic: dt.marketingMainPic,
                        rebate: dt.actualPrice,
                        coupon: {
                            activityId: libCollect.getCouponId(dt.couponLink),
                            start: Date.parse(new Date(dt.couponStartTime)),
                            end: Date.parse(new Date(dt.couponEndTime)),
                            amount: parseFloat(dt.couponPrice)
                        },
                        tkCoInfo: {
                            name: dt.teamName,
                            url: "http://www.dataoke.com/item?id=" + dt.id,
                            content: ''
                        }
                    })
                } else cb("大淘客平台：" + res.msg)
            } else cb("大淘客查询出现问题")
        })
    },
    getXuandanInfo: function getXuandanInfo(cb) {
        var url = 'http://api.xuandan.com/DataApi/Checkitem?appkey=utfic1soaj&id=' + libCollect.getItemId();
        bgWork.get(url, "json", function (sign, res) {
            //  console.log('选单网',sign, res)
            if (!sign && res) {
                if (res.error == 0 && res.msg == '在线') {
                    var dt = res.data[0];
                    if (dt.ActLink) {
                        couponurls = dt.ActLink
                        // console.log('选单网url',couponurls)
                    }
                    cb(null, {
                        name: '选单网',
                        desc: '',
                        pic: '',
                        rebate: dt.LastPrice,
                        coupon: {
                            activityId: libCollect.getCouponId(dt.ActLink),
                            start: Date.parse(new Date(dt.BeginDate)),
                            end: Date.parse(new Date(dt.EndDate)),
                            amount: 0
                        },
                        tkCoInfo: {
                            name: dt.TeamName,
                            url: "http://www.xuandan.com/Detail.html?id=" + dt.ID,
                            content: ''
                        }
                    })
                } else cb('选单网没有这个商品')
            } else cb('选单网出现问题')
        })
    },
    getCategory: function getCategory(cb) {
        var cateid = '',
            userid = libCollect.getSellerId(),
            goodid = libCollect.getItemId();
        $('script').each(function () {
            var cid = libCollect.getCategoryId(this.text);
            if (null != cid) cateid = cid
        });
        var turl = "http://plugin.qly360.com/productDetailList_UC.do?spid=" + goodid + "&userid=" + userid + "&category=-&cate=" + cateid + "&delist=-";
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res) {
                var obt = {
                    category: res[0].category,
                    unshelve: res[0].delist
                };
                cb(null, obt)
            } else cb("没有数据")
        })
    },
    getCategory2: function getCategory2(cb) {
        var data = {
            apikey: 'cE7DPwdtVEfvvqNok6JJZXmVCvGzxA2A',
            num_iids: libCollect.getItemId()
        };
        var url = "http://api.tbk.dingdanxia.com/tbk/item_info?";
        bgWork.get(url + urlParam(data), "json", function (sign, res) {
            if (!sign && res) {
                var dt = res.data[0];
                cb(null, dt.cat_name + "->" + dt.cat_leaf_name)
            } else cb("订单侠接口出现问题")
        })
    },
    getTKeasyInterface: function getTKeasyInterface(cb) {
        var gid = libCollect.getItemId(),
            sid = libCollect.getSellerId();
        var url = "https://www.tkeasy.com/interface/ItemTuiRecord?itemid=" + gid + "&sellerid=" + sid;
        bgWork.get(url, "json", function (sign, res) {
            cb(!sign && res && res.ok ? 1 : 0)
        })
    },
    trendBox: function trendBox() {
        var gid = libCollect.getItemId();
        spreadformWork.getTKeasyInterface(function (symbol) {
            if (symbol) {
                dialog.iframe({
                    title: '销量与传播记录',
                    width: '600px',
                    length: '90%',
                    url: "https://www.tkeasy.com/item/" + gid
                })
            } else dialog.msg('该商品没有任何联盟群传播记录')
        })
    },
    docWork: function docWork(intro, pic) {
        if (intro != "") {
            var reg = /http(s)?:\/\/img.alicdn.com\/.*?.jpg/;
            var _intro = pic != "" ? intro.replace(reg, pic) : intro;
            var tHtml = "<li id=\"docTag\" class=\"lt_column\"><div class=\"title\"><i class=\"icon doc\"></i>文案<div class=\"tooltiptext\"><span class=\"layui-layer-content\">" + _intro + "</span></div></div></li>";
            $(".tagbar").append(tHtml)
        }
    },
    showTable1: function showTable1(item) {
        var _title = item.title ? item.title : "满" + checkNum(item.applyAmount) + "减" + checkNum(item.amount),
            _time = new Date(item.start).format("MM.dd") + "-" + new Date(item.end).format("MM.dd"),
            _taken = item.receive + "/" + item.total,
            _copyurl = item.url,
            _aid = item.activityId ? item.activityId : 0,
            _type = item.type,
            tabtxt = '';
        switch (item.type) {
            case 0:
                tabtxt = "<tr><td id=\"coupname\">" + _title + "<div class=\"tip\">ID_" + _aid + "</div></td><td>店铺劵</td><td>" + _time + "</td><td>" + _taken + "</td><td><a class=\"" + (_copyurl ? "couponurl" : "") + "\" data-clipboard-text=\"" + _copyurl + "\">点击复制</a></td><td><a class=\"couponwork\" id=\"aid-" + _aid + "-" + _type + "\">点击领劵</a></td></tr>";
                break;
            case 1:
                tabtxt = "<tr><td id=\"coupname\">" + _title + "<span class=\"coup orger\">阿</span><div class=\"tip\">ID_" + _aid + "</div></td><td><span class=\"simp-0\">单品券</span></td><td>" + _time + "</td><td>" + _taken + "</td><td><a class=\"" + (_copyurl ? "couponurl" : "") + "\" data-clipboard-text=\"" + _copyurl + "\">点击复制</a></td><td><a class=\"couponwork\" id=\"aid-" + _aid + "-" + _type + "\">点击领劵</a></td></tr>";
                break;
            case 3:
                tabtxt = "<tr><td>" + _title + "<span class=\"coup blue\">阿</span></td><td><span class=\"simp-2\">阿里劵</span></td><td>" + _time + "</td><td>" + _taken + "</td><td>-</td><td><a class=\"couponwork\" id=\"aid-" + _aid + "-" + _type + "\">点击领劵</a></td></tr>";
                break
        }
        $("#couponheader").append(tabtxt);
        couponWork.nums++
    },
    showTable2: function showTable2(title, item) {
        var link, type, tabtxt, goodsurlc;
        switch (title) {
            case '实惠猪':
                link = 'http://www.shihuizhu.com/auth/login', type = 1,
                    goodsurlc = "http://shihuizhu.com/details?id=" + libCollect.getItemId();
                break;
            case '好单库':
                link = 'https://publish.haodanku.com/index/proving.html', type = 2,
                    goodsurlc = "https://www.haodanku.com/item/all_index?keyword=" + libCollect.getItemId();
                break;
            case '大淘客':
                link = 'http://www.dataoke.com/login', type = 3,
                    goodsurlc = "http://www.dataoke.com/xp/search/?page=1&sortType=4&keywords=" + libCollect.getItemId();
                break;
            case '选单网':
                link = 'http://fd.xuandan.com/NewManage/AddGoods', type = 4,
                    goodsurlc = "http://www.xuandan.com/allindex.html?key=" + libCollect.getItemId();
                break
        }
        // console.log('type',type,'item',item)
        if (item == null) {
            tabtxt = "<div><div class=\"col-1\"><i class=\"icon i-" + type + "\"></i> " + title + " </div><div class=\"col-2\"><div class=\"cell-2\"><a href=\"" + link + "\" target=\"_blank\" class=\"special\">去放单</a></a></div></div></div>"
        } else {
            var price = item.rebate,
                coupon = item.coupon.amount == 0 ? '-' : item.coupon.amount,
                time = new Date(item.coupon.end).format("MM-dd"),
                url = item.tkCoInfo.url,
                name = item.tkCoInfo.name,
                aclass = '';
            if (name == '我要担保') aclass = 'special';
            tabtxt = "<li><div><div class=\"col-1\"><i class=\"icon i-" + type + "\"></i> " + title + " </div><div class=\"col-3\"><div class=\"cell-1\"><a href='" + goodsurlc + "' target='_blank' rel='noopener noreferrer' style='text-decoration: none;'>" + price + "元 </a></div><div class=\"cell-2\"><a href='" + couponurls + "' target='_blank' rel='noopener noreferrer' style='text-decoration: none;'> 券 " + coupon + "元 </a></div><div class=\"cell-3\"> " + time + " </a> 到期 </div><div class=\"cell-4\"><a href=\"" + url + "\" target=\"_blank\" class=\"" + aclass + "\"> " + name + " </a></div></div></div></li>"
        }
        // console.log('type',type)
        // console.log('tabtxt',tabtxt)
        $("#spread-" + type).html(tabtxt)
    },
    getShiHuiZhuRank: function getShiHuiZhuRank(cb) {
        var timestamp = parseInt(new Date().valueOf() / 1000);
        var url = 'http://api-test.shihuizhu.com/home.rank/salesNum?',
            data = {
                min_price: '',
                max_price: '',
                order: '',
                coupon_money: '',
                ratio: '',
                final_sales: '',
                cate: '',
                page: 1,
                limit: 60,
                keywords: '',
                type: 'hour',
                shop_name: '',
                is_chaoshi: 0,
                is_douyin: 0,
                hk: 0,
                is_dx: 0,
                is_wechat: 0,
                time: timestamp
            };
        var strParam = urlParam(data);
        var sign = MD5(strParam + '&key=shihuizhubangbang123');
        url = url + urlParam(data) + '&sign=' + sign;
        bgWork.get(url, 'json', function (s, n) {
            if (!s && n) {
                if (n.code == 0 && Array.isArray(n.data.data)) {
                    var list = [];
                    n.data.data.map(function (dt) {
                        list.push({
                            id: dt.id,
                            title: dt.sub_title,
                            img: dt.thumb,
                            link: dt.url,
                            sales: dt.lately_sales,
                            rebate: dt.price,
                            ratiotype: dt.ratio_type,
                            couponleft: dt.coupon_left,
                            coupontotal: dt.coupon_total,
                            couponmoney: dt.coupon_money,
                            comments: dt.comments,
                            tkynums: dt.tky_nums,
                            saleall: dt.final_sales,
                            shopname: dt.shop_name,
                            username: dt.username,
                            hasDoc: dt.is_delicacy == 1 ? 1 : 0,
                            istmall: dt.url.indexOf('taobao.com') > 0 ? 0 : 1,
                            rate: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? dt.dx_ratio : dt.ratio,
                            hasdx: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? 1 : 0
                        })
                    });
                    cb(null, list)
                } else cb('没有数据')
            } else cb('没有数据')
        })
    },
    showRanks: function showRanks() {
        var $this = spreadformWork;
        $this.getShiHuiZhuRank(function (sign, list) {
            if (!sign && Array.isArray(list)) {
                var index = 0;
                list.map(function (item) {
                    var link = "http://www.shihuizhu.com/details?id=" + item.id,
                        salenum = item.saleall,
                        commnum = item.comments;
                    if (salenum >= 10000) {
                        salenum = Math.floor(salenum / 1000) / 10 + '万'
                    }
                    if (commnum >= 10000) {
                        commnum = Math.floor(commnum / 1000) / 10 + '万'
                    }
                    var boxtxt = "\n                        <div class=\"card-box\" id=\"card-ltrank2-" + index + "\">\n                            <div class=\"card-img\">\n                                <a target=\"_blank\" href=\"" + link + "\">\n                                    <span class=\"card-label\">" + (index + 1) + "</span>    \n                                    " + (item.hasDoc ? '<span class="card-doc">精编文案</span>' : '') + "  \n                                    <img class=\"\" src=\"" + item.img + "\"> </a>\n                            </div>\n                            <div class=\"card-text\"><i class=\"" + (item.istmall ? 'tm' : 'tb') + "\"></i>\n                                <p class=\"card-name\" title=\"" + item.title + "\">" + item.title + "</p>\n                                <p class=\"card-sales\">近2小时销售<span>" + item.sales + "</span>件</p>\n                            </div>\n                            <div class=\"card-arae\">\n                                <ul>\n                                    <li class=\"ifshow\"> <span class=\"above\">￥" + item.rebate + "</span> <span class=\"under\">券后价</span> </li>\n                                    <li class=\"rg\"> <span class=\"above\">" + item.rate + "%</span> <span class=\"under\">" + item.ratiotype + "</span> </li>\n                                </ul>\n                            </div>\n                            <div class=\"card-line\">\n                                <p class=\"card-info\">券<span class=\"bet\">￥" + item.couponmoney + "</span>月销<span class=\"bet\">" + salenum + "</span>\n                                </p>\n                                <i class=\"more-icon\" id=\"more-rank2-" + index + "\"></i>\n                            </div>\n                            <div class=\"card-cbox\">\n                                <p class=\"item-info\">余券量<span class=\"bet\">" + item.couponleft + "/" + item.coupontotal + "</span></p>\n                                <p class=\"item-info\">评价<span class=\"bet\">" + commnum + "</span></p>\n                                <p class=\"item-info\">联盟<span class=\"bet\">" + item.tkynums + "</span></p>\n                                <p class=\"item-info\">店铺<span class=\"bet\">" + item.shopname + "</span></p>\n                                <p class=\"item-info\">放单人<span class=\"bet\">" + item.username + "</span></p>\n                            </div>\n                        </div>";
                    $(".ltrank2").append(boxtxt);
                    index++
                });
                $("i.more-icon").mouseenter(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank2') {
                        var tname = 'card-' + tidss[1] + '-' + tidss[2];
                        $("#" + tname).css("height", "374px")
                    }
                });
                $(".card-box").mouseleave(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank2') {
                        var h = $(this).height();
                        h != 292 && $(this).css("height", "274px")
                    }
                });
                $(".ltrank2").next().removeClass("pluginclear")
            }
        })
    },
    getShiHuiZhuPos: function getShiHuiZhuPos(cb) {
        var url = 'http://api-test.shihuizhu.com/home.rank/getRank?gid=' + libCollect.getItemId();
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取用户信息失败')
        })
    },
    getShiHuiZhuUser: function getShiHuiZhuUser(uid, cb) {
        var url = 'http://api-test.shihuizhu.com/home.member/profile?uid=' + uid;
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取用户信息失败')
        })
    },
    getShiHuiZhuUserGoods: function getShiHuiZhuUserGoods(uid, cb) {
        var timestamp = parseInt(new Date().valueOf() / 1000);
        var url = 'http://api-test.shihuizhu.com/home.goods/goodsList?',
            data = {
                uid: uid,
                time: timestamp
            };
        var strParam = urlParam(data);
        var sign = MD5(strParam + '&key=shihuizhubangbang123');
        url = url + urlParam(data) + '&sign=' + sign;
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取用户信息失败')
        })
    },
    getGoodDaySale: function getGoodDaySale(cb) {
        var url = 'http://api-test.shihuizhu.com/home.sales/todaySales?gid=' + libCollect.getItemId();
        bgWork.get(url, 'json', function (sign, res) {
            !sign && res && res.code == 0 && res.hasOwnProperty("data") > 0 ? cb(null, res.data) : cb('获取今日销量失败')
        })
    },
    contractorWork: function contractorWork(uid) {
        var isexpire = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
        var $this = spreadformWork
    },
    showTodaySale: function showTodaySale(sales) {
        var $this = spreadformWork,
            $that = historyWork,
            $chart = echarts.init(document.getElementById("todaychart")),
            $option = $that.initOption(),
            xdata = [],
            ydata = [];
        sales && Array.isArray(sales) && sales.map(function (item) {
            xdata.push(new Date(item.add_time * 1000).format("hh:ss"));
            ydata.push(item.sales_volume)
        });
        $option = $that.setOption($option, {
            x: xdata,
            y: ydata,
            text: '销量'
        });
        $chart.setOption($option)
    },
    showUserGoods: function showUserGoods(uid) {
        var $this = spreadformWork;
        $this.getShiHuiZhuUserGoods(uid, function (sign, res) {
            if (!sign && res && res.hasOwnProperty("page_data") > 0 && Array.isArray(res.page_data)) {
                var list = [];
                res.page_data.map(function (dt) {
                    list.push({
                        id: dt.id,
                        title: dt.sub_title,
                        img: dt.thumb,
                        link: dt.url,
                        sales: dt.today_sales,
                        rebate: dt.price,
                        ratiotype: dt.ratio_type,
                        couponleft: dt.coupon_left,
                        coupontotal: dt.coupon_total,
                        couponmoney: dt.coupon_money,
                        comments: dt.comments,
                        tkynums: dt.tky_nums,
                        saleall: dt.final_sales,
                        shopname: dt.shop_name,
                        username: dt.username,
                        hasDoc: dt.is_delicacy == 1 ? 1 : 0,
                        istmall: dt.url.indexOf('taobao.com') > 0 ? 0 : 1,
                        rate: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? dt.dx_ratio : dt.ratio,
                        hasdx: parseFloat(dt.dx_ratio) > parseFloat(dt.ratio) ? 1 : 0
                    })
                });
                var index = 0;
                list.map(function (item) {
                    var link = "http://www.shihuizhu.com/details?id=" + item.id,
                        salenum = item.saleall,
                        commnum = item.comments;
                    if (salenum >= 10000) salenum = Math.floor(salenum / 1000) / 10 + '万';
                    if (commnum >= 10000) commnum = Math.floor(commnum / 1000) / 10 + '万';
                    var boxtxt = "\n                            <div class=\"card-box\" id=\"card-rank1-" + index + "\">\n                                <div class=\"card-img\">\n                                    <a target=\"_blank\" href=\"" + link + "\">   \n                                        " + (item.hasDoc ? '<span class="card-doc">精编文案</span>' : '') + "  \n                                        <img class=\"\" src=\"" + item.img + "\">\n                                    </a>\n                                </div>\n                                <div class=\"card-text\"> <i class=\"" + (item.istmall ? 'tm' : 'tb') + "\"></i>\n                                    <p class=\"card-name\" title=\"" + item.title + "\">" + item.title + "</p>\n                                    <p class=\"card-sales\">今日销售<span>" + item.sales + "</span>件</p>\n                                </div>\n                                <div class=\"card-arae\">\n                                    <ul>\n                                        <li class=\"ifshow\"> <span class=\"above\">￥" + item.rebate + "</span> <span class=\"under\">券后价</span> </li>\n                                        <li class=\"rg\"> <span class=\"above\">" + item.rate + "%</span> <span class=\"under\">" + item.ratiotype + "</span> </li>\n                                    </ul>\n                                </div>\n                                <div class=\"card-line\">\n                                    <p class=\"card-info\">券<span class=\"bet\">￥" + item.couponmoney + "</span>月销<span class=\"bet\">" + salenum + "</span>\n                                    </p>\n                                    <i class=\"more-icon\" id=\"more-rank1-" + index + "\"></i>\n                                </div>\n                                <div class=\"card-cbox\">\n                                    <p class=\"item-info\">余券量<span class=\"bet\">" + item.couponleft + "/" + item.coupontotal + "</span></p>\n                                    <p class=\"item-info\">评价<span class=\"bet\">" + commnum + "</span></p>\n                                    <p class=\"item-info\">联盟<span class=\"bet\">" + item.tkynums + "</span></p>\n                                    <p class=\"item-info\">店铺<span class=\"bet\">" + item.shopname + "</span></p>\n                                    <p class=\"item-info\">放单人<span class=\"bet\">" + item.username + "</span></p>\n                                </div>\n                            </div>";
                    $(".rank1").append(boxtxt);
                    index++
                });
                $("i.more-icon").mouseenter(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank1') {
                        var tname = 'card-' + tidss[1] + '-' + tidss[2];
                        $("#" + tname).css("height", "374px")
                    }
                });
                $(".card-box").mouseleave(function () {
                    var tid = this.id;
                    var tidss = tid.split('-');
                    if (tidss[1] == 'rank1') {
                        var h = $(this).height();
                        h != 292 && $(this).css("height", "274px")
                    }
                })
            }
        })
    },
    showContractor: function showContractor(uid, sales, user, pos) {
        var sales2h = 0,
            salesday = 0,
            catestr = '',
            direstr = '',
            posday = '-',
            posnow = '-';
        if (sales && sales.length > 0) {
            salesday = sales[sales.length - 1].sales_volume - sales[0].sales_volume;
            var time2h = new Date().valueOf() / 1000 - 2 * 60 * 60;
            var _saleitem = sales.find(function (item) {
                return item.add_time - time2h >= 0
            });
            if (_saleitem) {
                sales2h = sales[sales.length - 1].sales_volume - _saleitem.sales_volume
            }
        }
        var text = user ? "此商品由" + user.team_name + "团队担保，请放心推广" : '此商品暂无担保人，请谨慎推广！';
        var sign = user ? 'covenant' : 'warring';
        if (user && user.cate && user.cate != "") {
            catestr = user.cate.replace(/,/g, '</span><span>');
            catestr = '<span>' + catestr + '</span>'
        }
        if (user) {
            if (user.phone != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire phone\"></i>" + user.phone + "</div>"
            }
            if (user.team_qq != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire qq\"></i>" + user.team_qq + "</div>"
            }
            if (user.team_wechat != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire wechat\"></i>" + user.team_wechat + "</div>"
            }
            if (user.team_dingtalk != "") {
                direstr += "<div class=\"col\"> <i class=\"icon dire dingding\"></i>" + user.team_dingtalk + "</div>"
            }
        }
        if (pos) {
            posday = pos.today_rank == 0 ? '-' : pos.today_rank;
            posnow = pos.lately_rank == 0 ? '-' : pos.lately_rank
        }
        var brandHtml = "<div class=\"LTcontact\">\n                <div class=\"left\">\n                    <div class=\"title\"><i class=\"icon logo\"></i>乐推指数\n                    <span>全网排名<sp>No." + posday + "</sp>实时排名<sp>No." + posnow + "</sp>\n                    </span></div>\n                    <div class=\"line\">\n                        <div id=\"\" class=\"ban\">近2小时销量\n                            <sp>" + sales2h + "</sp>\n                        </div>\n                        <div class=\"ban\">全天销量\n                            <sp>" + salesday + "</sp>\n                        </div>\n                        <div id=\"todaychart\" class=\"panel p-1\"></div>\n                    </div>\n                </div>\n                <div class=\"right\"><i class=\"icon " + sign + "\"></i>\n                    <div class=\"text\">" + text + "</div>\n                </div>\n            </div>";
        $("div.tb-detail-hd").length > 0 ? $("div.tb-detail-hd").before(brandHtml) : $("div.tb-title").before(brandHtml);
        if (user) {
            var panelHtml = "<div class=\"panel p-3\"> \n                    <img class=\"avatar\" src=\"" + user.user_img + "\">\n                    <div class=\"person\">\n                        <div class=\"name\">" + user.team_name + "</div>\n                        <div class=\"locat\"> <i class=\"icon map\"></i>" + (user.area == '_' ? '中国' : user.area) + "</div>\n                        <div class=\"item\">\n                            <div class=\"item_left\">团队介绍：</div>\n                            <div class=\"item_right\">" + user.team_desc + "</div>\n                        </div>\n                        <div class=\"item\">\n                            <div class=\"item_left\">擅长领域：</div>\n                            <div class=\"item_right\">" + catestr + "</div>\n                        </div>\n                        <div class=\"item\">\n                            <div class=\"item_left\">联系方式：</div>\n                            <div class=\"item_right\">" + direstr + "</div>\n                        </div>\n                        <div class=\"point\">推广中如遇售后/定向等问题可联系该团队，联系备注乐推！</div>\n                    </div>\n                    <div class=\"mailme\">TA的商品</div>\n                    <div class=\"rank1 cab\"></div>\n                </div>";
            $("i.covenant").parent().append(panelHtml)
        } else {
            var link = 'http://www.shihuizhu.com/details?id=' + libCollect.getItemId();
            var _panelHtml = "<div class=\"panel p-2\">\n                    <a class=\"sponsor\" href=\"" + link + "\" target=\"_blank\">\n                    <img src=\"http://cdn.shihuizhu.net/img/guarantee_bg_v1.db2a749.png\">\n                        我要担保\n                    </a>\n                </div>";
            $("i.warring").parent().append(_panelHtml)
        }
        $("div.text").mouseenter(function () {
            $(this).parent().children(".panel").addClass("show")
        });
        $("div.line").mouseenter(function () {
            $(this).children(".panel").addClass("show")
        });
        $("div.panel").mouseleave(function () {
            $(this).removeClass("show")
        });
        sales && sales.length > 0 && spreadformWork.showTodaySale(sales);
        spreadformWork.showUserGoods(uid)
    },
    GetTagByClassUsingRegex: function GetTagByClassUsingRegex(tag, cls, html, num) {
        let str = html
        var reg = new RegExp("<" + tag + "[^>]*class[\\s]?=[\\s]?['\"]" + cls + "[^'\"]*['\"][\\s\\S]*?<\/" + tag + ">", "g");
        var reg2 = new RegExp("<" + tag + "[^>](.*?)<\/" + tag + ">", "g")
        if (num === 1) {
            return str.match(reg2) //返回指定的 tag
        }
        if (num === 2) {
            var result = str.replace(/<[^>]+>/g, "")
            return result
        }
        // if(num === 3){
        //     var result = str.replace(/<[^>]+>/g,"")
        //     return result
        // }
        // return html.replace(reg, '') //删除指定类名的 tag
        return str.match(reg) //返回指定类名的 tag
    }
};
var nodeWork = {
    host: 'http://node.yiquntui.com',
    superSearch: function superSearch(cb) {
        var $this = nodeWork,
            link = libCollect.getSimpeLink(window.location.href);
        var url = $this.host + '/api/superSearch?link=' + encodeURIComponent(link);
        bgWork.get(url, "json", function (s, n) {
            !s && n ? cb(null, n.message) : cb('没有数据')
        })
    },
    goodSale: function goodSale(cb) {
        var $this = nodeWork;
        var url = $this.host + '/api/goodSale?goodid=' + libCollect.getItemId();
        bgWork.get(url, "json", function (s, n) {
            !s && n ? cb(null, n.data) : cb('没有数据')
        })
    },
    contentData: function contentData(cb) {
        var $this = nodeWork,
            shopid = /shopId=(\d+)/.exec($("meta[name='microscope-data']").attr('content'))[1],
            sellerid = libCollect.getSellerId();
        var url = $this.host + '/api/contentData?shopid=' + shopid + '&sellerid=' + sellerid;
        bgWork.get(url, "json", function (s, n) {
            !s && n ? cb(null, n.data) : cb('没有数据')
        })
    }
};
var serverWork = {
    net: function net(url, data) {
        bgWork.postjson(url, JSON.stringify(data), function (s, n) { })
    },
    addContact: function addContact(data) {
        var url = 'http://cai-api.yiquntui.com/index/index/addQicc',
            $this = serverWork;
        $this.net(url, data)
    },
    addDxgood: function addDxgood(data) {
        var url = 'http://cai-api.yiquntui.com/index/index/addDxGood',
            $this = serverWork;
        $this.net(url, data)
    },
    addIntro: function addIntro(data) {
        var url = 'http://cai-api.yiquntui.com/index/index/addWenan',
            $this = serverWork;
        $this.net(url, data)
    },
    addTempGood: function addTempGood(data) {
        var url = 'http://cai-api.zuanting.test/index/index/addTempGood',
            $this = serverWork;
        $this.net(url, data)
    },
    addDxcamp: function addDxcamp(data) {
        var url = 'http://open-api.shihuizhu.com/material/add';
        bgWork.post(url, JSON.stringify(data), 'json', function (s, n) { })
    }
};
var contentWork = {
    html: "<div class=\"person_info\">\n            <div class=\"P_h1\">下单信息</div>\n            <div class=\"P_innerwrap\">\n                <div class=\"detail\">\n                    <ul class=\"ul_detail\" id=\"xddt\">\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-08\"></span><span class=\"item_title\">公司名</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-1-1\">--</span></div>\n                        </li>\n                        <li class=\"item turn\">\n                            <div class=\"item_left\"><span class=\"item_ico s-13\"></span><span class=\"item_title\">店铺名</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-1-2\">--</span></div>\n                        </li>\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-07\"></span><span class=\"item_title\">电话</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-1-3\">--</span></div>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n            <div class=\"P_h1\">预留信息</div>\n            <div class=\"P_innerwrap\">\n                <div class=\"detail\">\n                    <ul class=\"ul_detail\" id=\"alidt\">\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-01\"></span><span class=\"item_title\">QQ</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-4-1\">--</span></div>\n                        </li>\n                        <li class=\"item turn\">\n                            <div class=\"item_left\"><span class=\"item_ico s-02\"></span><span class=\"item_title\">微信</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-4-2\">--</span></div>\n                        </li>\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-03\"></span><span class=\"item_title\">微博</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-4-3\">--</span></div>\n                        </li>\n                        <li class=\"item turn\">\n                            <div class=\"item_left\"><span class=\"item_ico s-04\"></span><span class=\"item_title\">旺旺</span></div>\n                            <div class=\"item_right limitH\">\n                                <!--<span class=\"item_info\" id=\"p-info-4-4\">--</span>-->\n                                <button id=\"contDZ\" class=\"button-tiny\">尝试店长</button>\n                                <button id=\"contYY\" class=\"button-tiny\">尝试运营</button>\n                                <button id=\"contWW\" class=\"button-tiny\">店铺旺旺</button>\n                            </div>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n            <div class=\"P_h1\">京东万象</div>\n            <div class=\"P_innerwrap\">\n                <div class=\"detail\">\n                    <ul class=\"ul_detail\" id=\"wayjd\">\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-07\"></span><span class=\"item_title\">电话</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-5-1\">--</span></div>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n            <div class=\"P_h1\">前端号码</div>\n            <div class=\"P_innerwrap\">\n                <div class=\"detail\">\n                    <ul class=\"ul_detail\" id=\"qddt\">\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-07\"></span><span class=\"item_title\">电话</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-6-1\">--</span></div>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n            <div class=\"P_h1\">企查查</div>\n            <div class=\"P_innerwrap\">\n                <div class=\"detail\">\n                    <ul class=\"ul_detail\" id=\"qicc\">\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-08\"></span><span class=\"item_title\">公司名</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-3-1\">--</span></div>\n                        </li>\n                        <li class=\"item turn\">\n                            <div class=\"item_left\"><span class=\"item_ico s-09\"></span><span class=\"item_title\">法人</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-3-2\">--</span></div>\n                        </li>\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-10\"></span><span class=\"item_title\">注册资本</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-3-3\">--</span></div>\n                        </li>\n                        <li class=\"item turn\">\n                            <div class=\"item_left\"><span class=\"item_ico s-11\"></span><span class=\"item_title\">成立日期</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-3-4\">--</span></div>\n                        </li>\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-06\"></span><span class=\"item_title\">邮箱</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-3-5\">--</span></div>\n                        </li>\n                        <li class=\"item turn\">\n                            <div class=\"item_left\"><span class=\"item_ico s-07\"></span><span class=\"item_title\">电话</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-3-6\">--</span></div>\n                        </li>\n                        <li class=\"item\">\n                            <div class=\"item_left\"><span class=\"item_ico s-12\"></span><span class=\"item_title\">地址</span></div>\n                            <div class=\"item_right\"><span class=\"item_info\" id=\"p-info-3-7\">--</span></div>\n                        </li>\n                    </ul>\n                </div>\n            </div>\n        </div>",
    setText: function setText(index, list) {
        for (var i = 1; i <= list.length; i++) {
            var txt = isEmpty(list[i - 1]) ? '-' : list[i - 1];
            $("#p-info-" + index + "-" + i).text(txt)
        }
    },
    setHtml: function setHtml(index, list) {
        for (var i = 1; i <= list.length; i++) {
            var txt = isEmpty(list[i - 1]) ? '-' : list[i - 1];
            $("#p-info-" + index + "-" + i).html(txt)
        }
    },
    action: function action() {
        var $this = contentWork;
        dialog.msg("获取数据中...");
        $.map($(".item_info"), function (item) {
            $(item).text("读取中...")
        });
        nodeWork.contentData(function ($sign, $res) {
            if (!$sign && $res) {
                $this.littleWork($res, function (_sign, _res) {
                    if (!_sign && _res) {
                        var res = JSON.parse(_res);
                        // console.log('联系返回', res)

                        if ($.isEmptyObject(res)) {
                            $.map($(".item_info"), function (item) {
                                $(item).text("暂无")
                            });
                        }
                        if (res.hasOwnProperty("front")) {
                            $this.setText(6, [res.front.phone])
                        }
                        if (res.hasOwnProperty("order")) {
                            $this.setText(1, [res.order.corpname, res.order.shopname, res.order.phone]);
                            var status = res.order.wxstatus;
                            if (status == -1) $("#p-info-1-3").after('<span class="item_ico l-1"></span>');
                            else if (status == 1) $("#p-info-1-3").after("<span class=\"item_ico l-2\"></span><span class=\"item_info\">" + res.order.wxname + "</span>")
                        }
                        if (res.hasOwnProperty("qicc")) {
                            $this.setText(3, [res.qicc.companyname, res.qicc.corporation, res.qicc.registcapit, res.qicc.setupdate, res.qicc.mail, res.qicc.phone, res.qicc.address])
                        }
                        if (res.hasOwnProperty("wayjd")) {
                            $this.setText(5, [res.wayjd.phone])
                        }
                        if (res.hasOwnProperty("alimama")) {
                            $this.setText(4, [res.alimama.qq, res.alimama.wx, res.alimama.wb, res.alimama.ww])
                        } else $this.alicard()
                    }
                })
            }
        })
    },
    alicard: function alicard() {
        var $this = contentWork;
        if (aliContact && aliContact.hasOwnProperty('qq')) {
            $this.setText(4, [aliContact.qq, aliContact.wx, aliContact.wb]);
            var _data = {};
            _data.seller_id = libCollect.getSellerId();
            _data.alimama = JSON.stringify({
                qq: aliContact.qq,
                vx: aliContact.wx,
                wb: aliContact.wb,
                ww: aliContact.ww
            });
            serverWork.addContact(_data)
        } else {
            $this.setHtml(4, ['<a href="https://pub.alimama.com/" target="_blank">登陆阿里妈妈后可查看</a>', '<a href="https://pub.alimama.com/" target="_blank">登陆阿里妈妈后可查看</a>', '<a href="https://pub.alimama.com/" target="_blank">登陆阿里妈妈后可查看</a>'])
        }
    },
    showBox: function showBox() {
        var $this = contentWork;
        if (!layFlag) {
            layFlag = true;
            dialog.box({
                width: '400px',
                height: '750px',
                title: '信息',
                content: $this.html
            });
            $this.action()
        }
    },
    wangwangUrl: function wangwangUrl(type) {
        var shopname = window.location.href.indexOf("item.taobao.com") > 0 ? $("a.shop-name-link").text().trim() : $("a.slogo-shopname").text().trim();
        var txt = shopname + ":" + (type == 0 ? '店长' : '运营');
        return 'aliim:sendmsg?spm=&touid=cntaobao' + encodeURIComponent(txt)
    },
    littleWork: function littleWork(msg, cb) {
        var url = 'https://shihuizhu3920-1302253966.cos.ap-nanjing.myqcloud.com/bao',
            $this = contentWork;
        bgWork.get(url, '', function (s, n) {
            // console.log('联系返回',s,n)
            var sign = MD5(s.responseText).toUpperCase();
            var sign1 = sign.slice(0, 14) + new Date().format("hh"),
                sign2 = sign.slice(17, 31) + new Date().format("mm");
            var str = $this.aesCrypt(msg, sign1, sign2);
            var text = $this.theCode(str);
            cb(null, text)
        })
    },
    aesCrypt: function aesCrypt(data, key, iv) {
        var decrypt = CryptoJS.AES.decrypt(data, CryptoJS.enc.Utf8.parse(key), {
            iv: CryptoJS.enc.Latin1.parse(iv),
            mode: CryptoJS.mode.CBC,
            padding: CryptoJS.pad.Pkcs7
        });
        return decrypt.toString(CryptoJS.enc.Utf8)
    },
    theCode: function theCode(msg) {
        var key = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        var l = key.length;
        var b, b1, b2, b3, d = 0,
            s, str = '';
        for (var i = 0; i < msg.length; i++) {
            if (0 != (i + 1) % 4) {
                str += msg.charAt(i)
            }
        }
        s = new Array(Math.floor(str.length / 3));
        b = s.length;
        for (var i = 0; i < b; i++) {
            b1 = key.indexOf(str.charAt(d));
            d++;
            b2 = key.indexOf(str.charAt(d));
            d++;
            b3 = key.indexOf(str.charAt(d));
            d++;
            s[i] = b1 * l * l + b2 * l + b3
        }
        b = eval("String.fromCharCode(" + s.join(',') + ")");
        return b
    }
};
var salesWork = {
    action: function action() {
        $(".sales-sales").attr("style", "display:none;");
        $("#saleschart").attr("style", "display:none;");
        $(".lt_plats").attr("style", "display:block;");
        var $this = salesWork;
        $this.tkyInfo(function (sign, list) {
            if (!sign && Array.isArray(list)) {
                if (list.length > 0) {
                    var $begin = list.length > 10 ? list.length - 10 : 0,
                        $end = list.length;
                    list = list.slice($begin, $end);
                    var $chart = echarts.init(document.getElementById("saleschart")),
                        $option = $this.initOption();
                    $chart.setOption($option);
                    list.map(function (item) {
                        $(".sales-sales").children("ul").append("<li class=\"areasli\">" + item.day + "</li>")
                    });
                    $("li.areasli:last").addClass("sales-active");
                    $option = $this.setOption($option, {
                        x: list[list.length - 1].time,
                        y: list[list.length - 1].num
                    });
                    $chart.setOption($option);
                    $("li.areasli").click(function () {
                        var _this = this;
                        $.each($("li.areasli"), function (i, item) {
                            $(item).removeClass("sales-active")
                        });
                        $(this).addClass("sales-active");
                        list.map(function (item) {
                            if (item.day == $(_this).text()) {
                                $option = $this.setOption($option, {
                                    x: item.time,
                                    y: item.num
                                });
                                $chart.setOption($option)
                            }
                        })
                    })
                } else $(".chartbox2").addClass("nonnne")
            } else $(".chartbox2").addClass("nonnne")
        });
        $("li.salesli").click(function () {
            switch ($(this).text()) {
                case '推广平台':
                    $(".sales-sales").attr("style", "display:none;");
                    $("#saleschart").attr("style", "display:none;s");
                    $(".lt_plats").attr("style", "display:block;");
                    $.each($("li.salesli"), function (i, item) {
                        $(item).removeClass("sales-active")
                    });
                    $(this).addClass("sales-active");
                    break;
                case '群传播记录':
                    platformWork.trendBox();
                    spreadformWork.trendBox();
                    break;
                case '销量轨迹':
                    if ($("#saleschart").hasClass("nonnne")) {
                        dialog.msg("该商品没有任何联盟群传播记录")
                    } else {
                        $(".sales-sales").attr("style", "display:block;");
                        $("#saleschart").attr("style", "display:block;");
                        $(".lt_plats").attr("style", "display:none;");
                        $.each($("li.salesli"), function (i, item) {
                            $(item).removeClass("sales-active")
                        });
                        $(this).addClass("sales-active")
                    }
                    break
            }
        })
    },
    getNum: function getNum(str) {
        str = str.replace(/\r\n/g, "");
        str = str.replace(/(^\s+)|(\s+$)/g, "");
        var res = /销量\D+(\d+)/.exec(str);
        return res ? res[1] : 0
    },
    getTime: function getTime(str) {
        var $str = str.split(' ');
        return {
            day: $str[0],
            clock: $str[1]
        }
    },
    tkyInfo: function tkyInfo(cb) {
        bgWork.get("http://www.tkeasy.com/item/" + libCollect.getItemId(), "", function (sign, res) {
            if (sign) {
                var parser = new DOMParser(),
                    collect = [];
                var htmldoc = parser.parseFromString(sign.responseText, "text/html");
                var elms = htmldoc.getElementsByTagName("div");
                for (var n = 0; n < elms.length; n++) {
                    if (elms[n].className == 'renzhengdan') {
                        var _item = elms[n].parentNode;
                        _item = _item.previousSibling.previousSibling;
                        var day = /\d+-\d+-\d+/g.exec(_item.innerText)[0];
                        if (day == new Date().format("yyyy-MM-dd")) {
                            var gname = elms[n].innerText;
                            $("#panel-3").append("<div class=\"renzheng\"><span>" + gname + "</span></div>")
                        }
                        break
                    }
                }
                var tableDoc = htmldoc.getElementsByTagName("tbody");
                for (var n = tableDoc.length - 1; n >= 0; n--) {
                    var trdoc = tableDoc[n].getElementsByTagName("tr");
                    var trs = [],
                        sts = [],
                        day = '',
                        $last = 0;
                    for (var i = trdoc.length - 1; i >= 0; i--) {
                        var tddoc = trdoc[i].getElementsByTagName("td");
                        var times = salesWork.getTime(tddoc[0].innerText.trim()),
                            num = salesWork.getNum(tddoc[2].innerText.trim());
                        day = i == 0 && times.day;
                        if (num != 0) {
                            $last = salesWork.getNum(trdoc[i + 1 > trdoc.length - 1 ? trdoc.length - 1 : i + 1].innerText.trim());
                            trs.push(times.clock);
                            sts.push(num - $last)
                        }
                    }
                    collect.push({
                        day: day,
                        time: trs,
                        num: sts
                    })
                }
                cb(null, collect)
            } else cb('没有数据')
        })
    },
    initOption: function initOption() {
        return {
            tooltip: {
                trigger: "axis"
            },
            grid: {
                left: "10px",
                right: "18px",
                bottom: "10px",
                top: "10px",
                containLabel: !0
            },
            xAxis: {
                type: "category",
                boundaryGap: !1,
                data: [],
                splitLine: {
                    show: !0
                },
                axisLabel: {}
            },
            yAxis: {
                type: "value",
                min: 0,
                minInterval: 1
            },
            series: [{
                type: "line",
                data: [],
                markLine: {
                    itemStyle: {
                        normal: {
                            color: "#005bac"
                        }
                    }
                },
                areaStyle: {
                    normal: {
                        color: "#005bac"
                    }
                },
                lineStyle: {
                    normal: {
                        color: "#005bac"
                    }
                },
                itemStyle: {
                    normal: {
                        color: '#005bac'
                    }
                }
            }]
        }
    },
    setOption: function setOption(option, item) {
        var min = Math.min.apply(Math, _toConsumableArray(item.y)),
            max = Math.max.apply(Math, _toConsumableArray(item.y));
        var _min = Math.floor(min / 5) * 5,
            _max = Math.ceil(max / 5) * 5;
        option.xAxis.data = item.x;
        option.yAxis.min = _min;
        option.yAxis.max = _max;
        option.series = [{
            type: "line",
            name: "销量增量",
            data: item.y,
            markLine: {
                itemStyle: {
                    normal: {
                        color: "#005bac"
                    }
                }
            },
            areaStyle: {
                normal: {
                    color: "#005bac"
                }
            },
            lineStyle: {
                normal: {
                    color: "#005bac"
                }
            },
            itemStyle: {
                normal: {
                    color: '#005bac'
                }
            }
        }];
        return option
    }
};
var historyWork = {
    html: "<div class=\"sales-price\">\n            <ul>\n                <li class=\"liareas\">历史促销</li>\n                <li class=\"liareas\">历史劵后</li>\n                <li class=\"liareas\">促销价</li>\n                <li class=\"liareas\">劵后价</li>\n                <li class=\"liareas\">佣金</li>\n                <li class=\"liareas\">月销量</li>\n                <li class=\"liareas\">月增量</li>\n                <li class=\"liareas\">今日销量</li>\n                <li class=\"liareas\"><i class=\"icon present\"></i></li>\n            </ul>\n        </div>",
    boxhtml: "",
    action: function action() {
        var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
        var $this = historyWork,
            $chart = echarts.init(document.getElementById("historychart")),
            $option = $this.initOption(),
            $data = {};
        if (type == 0) {
            $("#historychart").before($this.html);
            $chart.setOption($option);
            $this.getdata(function (sign, obj) {
                $data.data1 = !sign && obj ? obj : null
            });
            $this.getdata2(function (sign, obj) {
                $data.data2 = !sign && obj ? obj : null;
                !sign && obj && $chart.setOption($this.setOption($option, {
                    x: obj.dts2,
                    y: obj.rbs,
                    text: '历史劵后'
                })),
                    $("li.liareas:eq(1)").addClass("sales-active")
            });
            $this.getdata3(function (sign, obj) {
                $data.data3 = !sign && obj ? obj : null
            });
            $("li.liareas").click(function () {
                var xdata = [],
                    ydata = [],
                    text = $(this).text();
                if ($data.hasOwnProperty("data1") && $data.data1 != null) {
                    switch (text) {
                        case '促销价':
                            xdata = $data.data1.dts;
                            ydata = $data.data1.prs;
                            break;
                        case '劵后价':
                            xdata = $data.data1.dts;
                            ydata = $data.data1.rbs;
                            break;
                        case '佣金':
                            xdata = $data.data1.dts;
                            ydata = $data.data1.rts;
                            break;
                        case '月销量':
                            xdata = $data.data1.dts;
                            ydata = $data.data1.sas;
                            break;
                        case '月增量':
                            xdata = $data.data1.dts;
                            ydata = $data.data1.sts;
                            break;
                        case '':
                            if (!layFlag) {
                                layFlag = true;
                                dialog.box({
                                    width: '600px',
                                    height: '575px',
                                    title: '消息',
                                    content: $this.boxhtml
                                })
                            }
                            break
                    }
                }
                if ($data.hasOwnProperty("data2") && $data.data2 != null) {
                    switch (text) {
                        case '历史促销':
                            xdata = $data.data2.dts1;
                            ydata = $data.data2.prs;
                            break;
                        case '历史劵后':
                            xdata = $data.data2.dts2;
                            ydata = $data.data2.rbs;
                            break
                    }
                }
                if ($data.hasOwnProperty("data3") && $data.data3 != null) {
                    switch (text) {
                        case '今日销量':
                            xdata = $data.data3.times;
                            ydata = $data.data3.sales;
                            break
                    }
                }
                if (text != '') {
                    $option = $this.setOption($option, {
                        x: xdata,
                        y: ydata,
                        text: text
                    });
                    $chart.setOption($option);
                    $.each($("li.liareas"), function (i, item) {
                        $(item).removeClass("sales-active")
                    });
                    $(this).addClass("sales-active")
                }
            })
        } else {
            $chart.setOption($option);
            $this.getdata2(function (sign, obj) {
                if (!sign && obj) {
                    $option = $this.setOption($option, {
                        x: obj.dts2,
                        y: obj.rbs,
                        text: '价格'
                    });
                    $chart.setOption($option);
                    $("#hitrend").text(obj.tend)
                }
            })
        }
    },
    getdata: function getdata(cb) {
        var $this = historyWork;
        nodeWork.goodSale(function (sign, res) {
            if (!sign && res) {
                var parObj = JSON.parse(res);
                if (parObj.hasOwnProperty("result")) {
                    var dt = JSON.parse(res).result,
                        rebates = [],
                        prices = [],
                        rates = [],
                        sales = [],
                        saletend = [],
                        days = [],
                        index = 0,
                        last_sale = 0;
                    if (dt && Array.isArray(dt)) {
                        var $list = [];
                        var firstItemDay = parseInt(dt[0]),
                            lastItemDay = parseInt(dt[dt.length - 1]);
                        if (firstItemDay > lastItemDay) {
                            dt = dt.reverse()
                        }
                        dt && dt.map(function (item) {
                            if (index == 0) {
                                last_sale = parseInt(item.sales)
                            } else {
                                last_sale = parseInt(dt[index - 1].sales)
                            }
                            index++;
                            $list.push({
                                rebate: item.last_price,
                                price: item.price,
                                rateper: parseFloat(item.ratio),
                                rate: Math.floor(parseFloat(item.last_price) * parseFloat(item.ratio)) / 100,
                                sale: item.sales,
                                saletend: parseInt(item.sales) - last_sale,
                                day: new Date(item.date).format("yyyy-MM-dd")
                            });
                            rebates.push(item.last_price), prices.push(item.price), rates.push(Math.floor(parseFloat(item.last_price) * parseFloat(item.ratio)) / 100), sales.push(item.sales), saletend.push(parseInt(item.sales) - last_sale), days.push(new Date(item.date).format("MM-dd"))
                        });
                        $this.boxhtml = $this.makeHtml($list.reverse());
                        cb(null, {
                            rbs: rebates,
                            prs: prices,
                            rts: rates,
                            sas: sales,
                            sts: saletend,
                            dts: days
                        })
                    } else cb('没有数据')
                } else cb('没有数据')
            } else cb('没有数据')
        })
    },
    getdata2: function getdata2(cb) {
        var obj = {
            methodName: "getBiJiaInfo",
            jsoncallback: "",
            p_url: window.location.href,
            title: encodeURIComponent($(document).attr("title"))
        };
        var turl = "https://bijiatool-v2.manmanbuy.com/ChromeWidgetServices/WidgetServices.ashx?" + urlParam(obj);
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res) {
                var od = {
                    data: res.jiagequshi,
                    data2: res.jiagequshiyh,
                    tend: res.qushi.substr(res.qushi.length - 2, 2)
                };
                var prices = [],
                    rebates = [],
                    days1 = [],
                    days2 = [],
                    arr1 = od.data.match(/\[(.*?)\]/g),
                    arr2 = od.data2.match(/\[(.*?)\]/g);
                if (Array.isArray(arr1) && Array.isArray(arr2)) {
                    var index1 = arr1.length > 240 ? arr1.length - 1 - 240 : 0,
                        index2 = arr2.length > 240 ? arr2.length - 1 - 240 : 0;
                    arr1 = arr1.slice(index1, arr1.length - 1);
                    arr2 = arr2.slice(index2, arr2.length - 1);
                    arr1.map(function (item) {
                        var collects = /\[(Date.UTC\(.*?\)),(.*?),(.*?)\]/g.exec(item);
                        prices.push(parseFloat(collects[2]));
                        days1.push(new Date(eval(collects[1])).format("MM-dd"))
                    });
                    arr2.map(function (item) {
                        var collects = /\[(Date.UTC\(.*?\)),(.*?),(.*?)\]/g.exec(item);
                        rebates.push(parseFloat(collects[2]));
                        days2.push(new Date(eval(collects[1])).format("MM-dd"))
                    });
                    cb(null, {
                        tend: od.tend,
                        prs: prices,
                        dts1: days1,
                        rbs: rebates,
                        dts2: days2
                    })
                } else cb('没有数据')
            } else cb('没有数据')
        })
    },
    getdata3: function getdata3(cb) {
        var url = "http://zhushou4.taokezhushou.com/api/v1/history/sale?goods_id=" + libCollect.getItemId() + "&date=";
        bgWork.get(url, "json", function (sign, res) {
            if (!sign && res && res.hasOwnProperty("code") && res.code == 200 && res.data.data.length > 0) {
                var _times = [],
                    _sales = [];
                res.data.data.map(function (item) {
                    _times.push(new Date(item.created_at).format("hh:ss"));
                    _sales.push(item.sale_num)
                });
                cb(null, {
                    times: _times,
                    sales: _sales
                })
            } else cb('没有数据')
        })
    },
    initOption: function initOption() {
        return {
            title: {
                subtext: ''
            },
            tooltip: {
                trigger: "axis"
            },
            grid: {
                left: '3%',
                right: '3%',
                bottom: '3%',
                top: '19%',
                containLabel: !0
            },
            xAxis: {
                type: "category",
                data: []
            },
            yAxis: {
                type: "value",
                min: 0,
                max: 100,
                splitArea: {
                    show: true
                }
            },
            series: [{
                type: "line",
                data: []
            }]
        }
    },
    setOption: function setOption(option, item) {
        var min = Math.min.apply(Math, _toConsumableArray(item.y)),
            max = Math.max.apply(Math, _toConsumableArray(item.y));
        var _min = Math.floor(min / 5) * 5,
            _max = Math.ceil(max / 5) * 5;
        option.xAxis.data = item.x;
        option.yAxis.min = _min;
        option.yAxis.max = _max;
        option.series = [{
            type: "line",
            name: item.text,
            stack: item.text,
            data: item.y,
            markPoint: {
                data: [{
                    type: 'max',
                    name: '最大值'
                }, {
                    type: 'min',
                    name: '最小值'
                }]
            },
            itemStyle: {
                normal: {
                    color: '#005bac'
                }
            },
            lineStyle: {
                normal: {
                    color: '#005bac',
                    hadowColor: 'rgba(0,0,0,0.2)',
                    shadowBlur: 12,
                    shadowOffsetX: 5,
                    shadowOffsetY: 5
                }
            }
        }];
        return option
    },
    makeHtml: function makeHtml(list) {
        var header = '<table class="board"><thead><tr><th style="width: 16%;">日期</th><th style="width: 14%;">劵后价</th><th style="width: 14%;">价格</th><th style="width: 14%;">销量</th><th style="width: 14%;">增量</th><th style="width: 14%;">佣金比例</th><th style="width: 14%;">佣金</th></tr></thead><tbody>',
            tailer = '</tbody></table>',
            tbtxt = '';
        list && list.map(function (item) {
            tbtxt += "<tr>\n                        <td>" + item.day + "</td>\n                        <td>" + item.rebate + "元</td>\n                        <td>" + item.price + "元</td>\n                        <td>" + item.sale + "件</td>\n                        <td><span class=\"simp-" + (item.saletend > 0 ? 1 : 0) + "\">" + item.saletend + " " + (item.saletend > 0 ? '↑' : '↓') + "</span></td>\n                        <td>" + item.rateper + "%</td>\n                        <td>" + item.rate + "元</td>\n                    </tr>"
        });
        return header + tbtxt + tailer
    }
};
var tkDocWork = {
    html: "<div class=\"YQTs-template-body\">\n        <div class=\"YQTs-template-l\" style=\"#hindeen#\">\n            <h4>优质图片（共#picnum#张）\n                <span><em id=\"zuo\">&lt;</em> <em id=\"you\">&gt;</em></span>\n            </h4>\n            <div class=\"YQTs-imgs-ul\" style=\"width: 370px; height: 92px; overflow: hidden\">\n                <div style=\"width: 600px\">\n                #pictext#\n                </div>\n            </div>\n            <div class=\"YQTs-img-copy\">\n                <div><img src=\"#initpic#\"></div><a id=\"imgTag\">复制图片</a></div>\n        </div>\n        <div class=\"YQTs-template-r\">\n            <h4>优质文案（共#intronum#条）</h4>\n            <div class=\"YQTs-text-ul\" style=\"max-height: 508px;\">\n            #introtext#\n            </div>\n        </div>\n    </div>",
    dataObj: {
        msg: '亲，文案正在读取中，请稍候再试~'
    },
    action: function action() {
        var $this = tkDocWork;
        $this.getDoc(function (sign, data) {
            if (!sign && data) {
                var index = 1,
                    introTxt = '',
                    picTxt = '',
                    _intros = [],
                    _pics = [];
                data.intros && data.intros.map(function (item) {
                    _intros.push(item.intro);
                    introTxt += "<div class=\"YQTs-text-li\"><span>" + index++ + ".</span>\n                        <textarea>" + item.intro + "</textarea> <a id=\"docTag\">复制</a></div>"
                });
                data.pics && data.pics.map(function (item) {
                    _pics.push(item.pic);
                    picTxt += "<a><img src=\"" + item.pic + "\"></a>"
                });
                serverWork.addIntro({
                    gid: libCollect.getItemId(),
                    intros: JSON.stringify(_intros),
                    pics: JSON.stringify(_pics)
                });
                if (introTxt != '' || picTxt != '') {
                    var content = $this.html;
                    var width = picTxt == '' ? '399px' : '804px';
                    content = content.replace("#introtext#", introTxt).replace("#intronum#", data.intros.length);
                    content = picTxt == '' ? content.replace("#hindeen#", "display:none") : content.replace("#pictext#", picTxt).replace("#hindeen#", "").replace("#picnum#", data.pics.length).replace("#initpic#", data.pics[0].pic);
                    $this.dataObj = {
                        W: width,
                        H: '604px',
                        content: content,
                        hasPic: picTxt != ''
                    }
                } else $this.dataObj.msg = '没有获取到优质文案'
            } else $this.dataObj.msg = '此商品没有对应文案'
        });
        $this.ltDoc();
        $this.countCommission()
    },
    showBox: function showBox() {
        var $this = tkDocWork;
        var obj = $this.dataObj;
        if (!isEmpty(obj) && obj.hasOwnProperty("content")) {
            if (!layFlag) {
                layFlag = true;
                dialog.box({
                    width: obj.W,
                    height: obj.H,
                    content: obj.content
                });
                obj.hasPic && $this.btnAction();
                $this.clipAction()
            }
        } else dialog.msg(obj.msg)
    },
    getDoc: function getDoc(cb) {
        var url = "http://zhushou4.taokezhushou.com/api/v1/template?id=" + libCollect.getItemId();
        bgWork.get(url, 'json', function (sign, res) {
            sign || 200 !== res.status ? cb("获取文案失败") : cb(null, res.data)
        })
    },
    btnAction: function btnAction() {
        $("#you").click(function () {
            var divs = $(".YQTs-imgs-ul div");
            var offset = $(".YQTs-imgs-ul div a").width() * -1;
            divs.stop().animate({
                marginLeft: offset
            }, "fast", function () {
                var firstItem = $(".YQTs-imgs-ul div a").first();
                divs.append(firstItem);
                $(this).css("margin-left", "0px")
            })
        });
        $("#zuo").click(function () {
            var divs = $(".YQTs-imgs-ul div");
            var offset = $(".YQTs-imgs-ul div a").width() * -1;
            var lastItem = $(".YQTs-imgs-ul div a").last();
            divs.prepend(lastItem);
            divs.css("margin-left", offset);
            divs.animate({
                marginLeft: "0px"
            }, "fast")
        });
        $(".YQTs-imgs-ul div a").click(function () {
            $.each($(".YQTs-imgs-ul div a"), function (i, item) {
                $(item).removeClass("YQTs-imgs-ul-active")
            });
            $(this).addClass("YQTs-imgs-ul-active");
            $(".YQTs-img-copy div img").attr("src", $($(this).children("img"))[0].src)
        })
    },
    clipAction: function clipAction() {
        var copyImg = new ClipboardJS('#imgTag', {
            target: function target() {
                var img = $(".YQTs-img-copy div img")[0].src;
                if (img.indexOf("alicdn.com") > 0) {
                    img = img.replace(/.*?\/\/.*?\//, "//imgproxy.qingtaoke.com/");
                    var n = /^http:/.test(img),
                        i = /^https:/.test(img);
                    return !1 === n && !1 === i ? img = "http:" + img : !1 === n && !0 === i && (img = img.replace(/^https/, "http")), img = img.replace(/[A-Z]/g, function (t) {
                        return "*" + t.toLowerCase()
                    }), $("body").append('<div class="LTplugin-wait-copyPic"><img src="' + img + '"></div>'), $(".LTplugin-wait-copyPic")[0]
                } else {
                    $("body").append('<div class="LTplugin-wait-copyPic"><img src="' + img + '"></div>');
                    return $(".LTplugin-wait-copyPic")[0]
                }
            }
        });
        copyImg.on("success", function (element) {
            dialog.msg("复制成功"), $(".LTplugin-wait-copyPic").remove(), element.clearSelection()
        });
        copyImg.on("error", function (element) {
            dialog.msg("复制失败"), $(".LTplugin-wait-copyPic").remove()
        });
        var copyDoc = new ClipboardJS('#docTag', {
            text: function text(element) {
                return $(element).prev().val()
            }
        });
        copyDoc.on("success", function (element) {
            dialog.msg("复制成功"), element.clearSelection()
        });
        copyDoc.on("error", function (element) {
            dialog.msg("复制失败")
        })
    },
    ltDoc: function ltDoc() {
        var url = 'http://api-test.shihuizhu.com/home.goods/community?gid=' + libCollect.getItemId();
        bgWork.get(url, 'json', function (sign, res) {
            if (!sign && res && res.hasOwnProperty("data")) {
                res.data.length !== 0 && ($(".fiche").children(":first").before('<i class="icon t-2" id="excellW" title="精编文案"></i>'), $(".fiche").addClass("third"), $(".fiche").before('<div class="tipbrand">大牛必选</div>'))
            }
        })
    },
    countCommission: function countCommission() {
        setTimeout(function () {
            var rate = parseFloat($(".info").children(".col-2").text());
            var commission = (rate * businessWork.getPrice() / 100).toFixed(2);
            $(".info").children(".col-5").text("(￥" + commission + ")")
        }, 2500)
    }
};
var similarGood = {
    action: function action() {
        similarGood.getHuoyuan(function (sign, list) {
            if (!sign && list) {
                similarGood.showOut(list)
            }
        })
    },
    aliEncode: function aliEncode() {
        var t, e, n, a, r, i = "taosellerran;" + new Date().getTime(),
            o = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",
            s = "",
            c = "",
            l = "",
            u = 0;
        do {
            t = i.charCodeAt(u++), e = i.charCodeAt(u++), c = i.charCodeAt(u++), n = t >> 2, a = (3 & t) << 4 | e >> 4, r = (15 & e) << 2 | c >> 6, l = 63 & c, isNaN(e) ? r = l = 64 : isNaN(c) && (l = 64), s = s + o.charAt(n) + o.charAt(a) + o.charAt(r) + o.charAt(l), t = e = c = "", n = a = r = l = ""
        } while (u < i.length);
        return s
    },
    getHuoyuan: function getHuoyuan(cb) {
        var turl = "https://open-s.1688.com/openservice/taoOfferSameSimilarBusinessService?fromOfferId=" + libCollect.getItemId() + "&needImage=true&_input_charset=utf-8&appName=taosellerran&appKey=" + similarGood.aliEncode();
        bgWork.get(turl, "json", function (sign, res) {
            if (!sign && res && res.msg == "OK") {
                var list = res.data.offerList;
                Array.isArray(list) ? cb(null, list) : cb("获取货源失败")
            } else cb("没有货源")
        })
    },
    showOut: function showOut(list) {
        var text = '';
        list.map(function (item) {
            text += "<div><a href=\"" + item.detailUrl + "\" target=\"_blank\"><img src=\"" + item.imageUrl + "\"></a><p>￥" + item.price + "</p></div>"
        });
        $(".items").append(text)
    }
};
var dealImg = {
    action: function action() {
        dealImg.showCopyPicBtn();
        dealImg.showCopyVideoBtn()
    },
    showCopyVideoBtnEvent: function showCopyVideoBtnEvent(t) {
        var e = !1;
        $(document).on("mouseenter", t, function () {
            e = !0;
            var n = $(this).offset().top - 45,
                i = $(this).offset().left + 110,
                r = $(this).find("source").attr("src");
            $(".LTplugin-video-ul").css({
                top: n + "px",
                left: i + "px"
            }), $(".LTplugin-video-link").val(r), $(".LTplugin-video-ul").show()
        }), $(document).on("mouseleave", t, function () {
            e = !1, setTimeout(function () {
                !e && $(".LTplugin-video-link").val(""), !e && $(".LTplugin-video-ul").hide()
            }, 500)
        }), $(document).on("mouseenter", ".LTplugin-video-ul", function () {
            e = !0, $(".LTplugin-video-ul").show()
        }), $(document).on("mouseleave", ".LTplugin-video-ul", function () {
            e = !1, $(".LTplugin-video-link").val(""), $(".LTplugin-video-ul").hide()
        })
    },
    showCopyVideoBtn: function showCopyVideoBtn() {
        var t = dealImg,
            d = dialog;
        $("body").append('<div class="LTplugin-video-ul"><ul><li><a class="LTplugin-copy-video">复制视频地址</a></li><li><a class="LTplugin-down-video">下载视频素材</a></li><li><input type="text" class="LTplugin-video-link"></li></ul></div>'), dealImg.showCopyVideoBtnEvent("div.lib-video video.lib-video");
        var n = new ClipboardJS(".LTplugin-copy-video", {
            text: function text() {
                return "https:" + $(".LTplugin-video-link").val()
            }
        });
        n.on("success", function (e) {
            d.msg("复制成功"), e.clearSelection()
        }), n.on("error", function (e) {
            d.msg("复制失败")
        });
        $(".LTplugin-down-video").click(function () {
            var t = "https:" + $(".LTplugin-video-link").val();
            var s = t.substring(t.lastIndexOf("/") + 1);
            s = s.substring(0, s.lastIndexOf("."));
            n = new XMLHttpRequest();
            n.open("GET", t, !0), n.responseType = "arraybuffer", n.onload = function () {
                if (4 === n.readyState && 200 === n.status) {
                    var t = this.response,
                        r = window.URL.createObjectURL(new Blob([t], {
                            type: "video/mp4"
                        })),
                        i = document.createElement("a");
                    i.download = s, i.href = r, i.style.display = "none", document.body.appendChild(i), i.click(), i.remove(), d.msg("下载成功")
                }
            }, n.send()
        })
    },
    showCopyPicBtnEvent: function showCopyPicBtnEvent(t) {
        var e = !1;
        $(document).on("mouseenter", t, function () {
            e = !0;
            var n = $(this).offset().top - 45,
                i = ".tb-booth a" === t ? $(this).offset().left + 110 : $(this).offset().left + $(this).width() + 10,
                r = ".tb-booth a" === t ? $(this).find("img").attr("src") : $(this).attr("src");
            ".tb-booth a" === t && ($(".LTplugin-copy-ul li").css("float", "left"), $(".LTplugin-copy-ul li:eq(1)").css("margin-left", "10px"));
            $(".LTplugin-copy-ul").css({
                top: n + "px",
                left: i + "px"
            }), $(".LTplugin-copy-img").val(r), $(".LTplugin-copy-ul").show()
        }), $(document).on("mouseleave", t, function () {
            e = !1, setTimeout(function () {
                !e && $(".LTplugin-copy-img").val(""), !e && $(".LTplugin-copy-ul").hide()
            }, 500)
        }), $(document).on("mouseenter", ".LTplugin-copy-ul", function () {
            e = !0, $(".LTplugin-copy-ul").show()
        }), $(document).on("mouseleave", ".LTplugin-copy-ul", function () {
            e = !1, $(".LTplugin-copy-img").val(""), $(".LTplugin-copy-ul").hide()
        })
    },
    showCopyPicBtn: function showCopyPicBtn() {
        var t = dealImg,
            d = dialog;
        $("body").append('<div class="LTplugin-copy-ul"><ul><li><a class="LTplugin-copy-pic">复制图片</a></li><li><a class="LTplugin-copy-url">复制图片地址</a></li><li><input type="text" class="LTplugin-copy-img"></li></ul></div>'), dealImg.showCopyPicBtnEvent(".tb-booth a"), dealImg.showCopyPicBtnEvent("#description > div.ltcontent img");
        var e = new ClipboardJS(".LTplugin-copy-pic", {
            target: function target(t) {
                var e = $(".LTplugin-copy-img").val();
                e = e.replace(/.*?\/\/.*?\//, "//imgproxy.qingtaoke.com/");
                var n = /^http:/.test(e),
                    i = /^https:/.test(e);
                return !1 === n && !1 === i ? e = "http:" + e : !1 === n && !0 === i && (e = e.replace(/^https/, "http")), e = e.replace(/[A-Z]/g, function (t) {
                    return "*" + t.toLowerCase()
                }), $("body").append('<div class="LTplugin-wait-copyPic"><img src="' + e + '"></div>'), $(".LTplugin-wait-copyPic")[0]
            }
        });
        e.on("success", function (e) {
            d.msg("复制成功"), $(".LTplugin-wait-copyPic").remove(), e.clearSelection()
        }), e.on("error", function (e) {
            d.msg("复制失败"), $(".LTplugin-wait-copyPic").remove()
        });
        var n = new ClipboardJS(".LTplugin-copy-url", {
            text: function text() {
                return $(".LTplugin-copy-img").val().split(".jpg")[0] + ".jpg"
            }
        });
        n.on("success", function (e) {
            d.msg("复制成功"), e.clearSelection()
        }), n.on("error", function (e) {
            d.msg("复制失败")
        })
    }
};
var businessWork = {
    hostDoms: [{
        dom: 'a.5smx.com',
        host: 'gateway-test.yiquntui.com'
    }, {
        dom: 'html.yiquntui.com',
        host: 'tc-tz.yiquntui.com'
    }, {
        dom: 'tz.zwk100.com',
        host: 'tz-api.zwk100.com'
    }, {
        dom: 'www.xinqilianmeng.com',
        host: 'tz-api.xinqilianmeng.com'
    }, {
        dom: 'www.zsnbgl.com',
        host: 'tz-api.zsnbgl.com'
    }, {
        dom: 'tz.qitui1688.com',
        host: 'api.qitui1688.com'
    }, {
        dom: 'luok.yiquntui.com',
        host: 'luok-api.yiquntui.com'
    }, {
        dom: 'www.zlstlm.com',
        host: 'tz-api.zlstlm.com'
    }, {
        dom: 'www.777328.cn',
        host: 'tz-api.777328.cn'
    }, {
        dom: 'html.uzheba.com',
        host: 'tz-api.uzheba.com'
    }, {
        dom: 'tz.yiquntui.com',
        host: 'tz-api.yiquntui.com'
    }, {
        dom: 'tz.tengcu.com',
        host: 'tz-api.tengcu.com'
    }, {
        dom: '',
        host: 'lt-tz.yiquntui.com'
    }],
    html: "<ul>\n  <li><div class=\"ifshow\">\n                <i class=\"icon l-1\"></i>\n                <i class=\"icon l-3\"></i>\n            </div></li>\n            <li><div class=\"ltmd\"><i class=\"icon c-warn\"></i>请登陆后使用以下功能</div></li>\n            <li><div class=\"rg\"></div></li>\n        </ul>",
    html2: "<div>拼接旺旺联系\n            <button id=\"contDZ\" class=\"shape contact\"><i class=\"icon b-0\"></i>尝试店长</button>\n            <button id=\"contYY\" class=\"shape contact\"><i class=\"icon b-0\"></i>尝试运营</button>\n            <button id=\"contWW\" class=\"shape contact\"><i class=\"icon b-0\"></i>店铺旺旺</button>\n        </div>\n           <div>更多联系方式\n            <button id=\"list_btn\" class=\"shape contact long\">查看联系方式\n                <i class=\"icon b-1\"></i><i class=\"icon b-2\"></i><i class=\"icon b-3\"></i><i class=\"icon b-4\"></i><i class=\"icon b-5\"></i><i class=\"icon b-6\"></i><i class=\"icon b-7\"></i><i class=\"icon b-8\"></i>\n            </button>\n        </div>",
    //<div>防撞单数据库\n            <span id=\"data-zd1\" class=\"line\">不可用</span>\n            <span id=\"data-zd2\" class=\"line\">不可用</span>\n        </div>\n 
    html3: "<div class=\"chooses\">\n            <ul>\n       <li class=\"lichooes active\">招商系统登陆</li>\n            </ul>\n        </div>\n        <div class=\"ltloginbox\"></div>",
    html4: '',
    // html4: "<block>团队标识</block><input id=\"txtDom\" type=\"text\" placeholder=\"请输入您团队的域名\">\n        </br>\n            <block>用户账号</block><input id=\"ltName\" type=\"text\" placeholder=\"请输入您的用户名\">\n        </br>\n            <block>用户密码</block><input id=\"ltuserPwd\" type=\"password\" placeholder=\"请输入您的密码\">\n        </br>    \n            <button id=\"login_tz\" class=\"shape loginit only\">登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录</button>",
    html5: "<block>用户账号</block><input id=\"ltName\" type=\"text\" placeholder=\"请输入您的用户名\">\n        </br>\n            <block>用户密码</block><input id=\"ltuserPwd\" type=\"password\" placeholder=\"请输入您的密码\">\n        </br>   \n            <button id=\"login_lt\" class=\"shape loginit\">登&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;录</button> \n            <button id=\"regist_lt\" class=\"shape loginit\">注&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;册</button>",
    html6: "<ul><li><div class=\"ifshow\">\n <i class=\"icon l-2\"></i>\n  <i class=\"icon l-3\"></i>\n   </div></li><li><div class=\"ltmd\"><i class=\"icon c-right\"></i>登陆成功</div></li><li>\n            <div class=\"rg\"><span id=\"login-out\">退出登录</span></div></li></ul>",
    html7: "<ul><li><div class=\"ifshow\">\n <i class=\"icon l-1\"></i>\n   <i class=\"icon l-4\"></i>\n  </div></li><li><div class=\"ltmd\"><i class=\"icon c-right\"></i>登陆成功</div></li><li>\n            <div class=\"rg\"><span id=\"login-out\">退出登录</span></div></li></ul>",
    // ' <li class=\"lichooes active\">乐推团长登陆<i class=\"icon\" title=\"乐推团长系统，是乐推官方推出的一套：高效的招商&#10;团长管理系统，集订单管理、业绩统计，权限分配，业绩&#10;排行，客户管理，推广平台等众多强大功能的招商系统！\"></i></li><div class=\"bubble\">了解团长</div>\n                '
    action: function action() {
        var $this = businessWork;
        $this.getInfo(function (info) {
            if (info) {
                $_userinfo = info;
                $(".ltuserbar").html($this.html);
                $(".ltuserwork").html($this.html2 + $this.html3);
                info.lt_type == 1 && ($(".lichooes:first").removeClass("active"), $(".lichooes:last").addClass("active"));
                $this.clicked(info.lt_type);
                $this.clickAction()
            }
        })
    },
    clicked: function clicked(type) {
        var $this = businessWork,
            info = $_userinfo;
        if (type == 0) {
            $this.tz_perpare();
            if (!isEmpty(info.lt_token) && !isEmpty(info.lt_dom) && !isEmpty(info.lt_host)) {
                $this.tz_net_center(info.lt_host, info.lt_token, function (sign, res) {
                    if (!sign && res && res.code == 0) {
                        $this.tz_step();
                        $this.page();
                        tzTimer = setInterval(function () {
                            businessWork.timerhandle()
                        }, 6000)
                    }
                })
            }
        } else if (type == 1) {
            $this.lt_perpare();
            info.lt_stamp > 0 && $this.lt_step()
        }
    },
    clickAction: function clickAction() {
        var $this = businessWork;
        $("li.lichooes").click(function () {
            var txt = $(this).text(),
                type = 0;
            $.each($("li.lichooes"), function (i, item) {
                $(item).removeClass("active")
            });
            $(this).addClass("active");
            switch (txt) {
                case '团长账号登陆':
                    type = 0;
                    break;
                case '招商系统登陆':
                    type = 1;
                    break
            }
            $this.clicked(type)
        })
    },
    getInfo: function getInfo(cb) {
        bgWork.getSettings("userInfo", function (str) {
            if (!isEmpty(str)) {
                var info = JSON.parse(str);
                info && validate(info) ? cb(info) : cb(null)
            }
        })
    },
    tz_perpare: function tz_perpare() {
        var $this = businessWork;
        //登录窗口默认显示html5
        $(".ltloginbox").html($this.html5);
        if (!isEmpty($_userinfo.lt_dom) && !isEmpty($_userinfo.lt_host) && !isEmpty($_userinfo.lt_uid) && !isEmpty($_userinfo.lt_pwd)) {
            $("#txtDom").val($_userinfo.lt_dom);
            $("#ltName").val($_userinfo.lt_uid);
            $("#ltuserPwd").val($_userinfo.lt_pwd)
        }
    },
    tz_step: function tz_step() {
        var $this = businessWork,
            info = $_userinfo;
        // console.log('$_userinfo', $_userinfo)
        $this.tz_net_status(info.lt_host, info.lt_token, function (_sign, _res) {
            if (!_sign && _res) {
                if (_res.code == 0) {
                    var n = void 0,
                        m = void 0,
                        e = void 0,
                        k = void 0;
                    switch (_res.data) {
                        case 1:
                            n = '可洽谈', m = '可合作';
                            e = 0, k = 0;
                            break;
                        case 2:
                            n = '洽谈中', m = '不可合作';
                            e = 1, k = 2;
                            break;
                        case 3:
                        case 4:
                        case 5:
                        case 6:
                            n = '保护中', m = '不可合作';
                            e = 2, k = 2;
                            break
                    }
                    $(".ltuserbar").html($this.html7);
                    $(".ltuserwork").html($this.html2);
                    $("#data-zd1").addClass("sip-" + e);
                    $("#data-zd2").addClass("sip-" + k);
                    $("#data-zd1").text(n);
                    $("#data-zd2").text(m);
                    IsLogin = true
                } else {
                    $this.tz_loginout()
                }
            }
        })
    },
    tz_loginout: function tz_loginout() {
        var $this = businessWork;
        $_userinfo.lt_token = '';
        bgWork.setSettings('userInfo', JSON.stringify($_userinfo));
        $this.action();
        clearInterval(tzTimer);
        IsLogin = false
    },
    tz_net_login: function tz_net_login(domain, username, userpwd, cb) {
        var $this = businessWork,
            _domain = domain.indexOf('shihuizhu.com') > 0 ? '' : domain;
        var $item = $this.hostDoms.find(function (item) {
            return item.dom == _domain
        });
        if (!isEmpty($item)) {
            var host = $item.host,
                data = {
                    username: encodeURIComponent(username),
                    password: userpwd,
                    domain: domain
                };
            var url = "http://" + host + "/gateway/login";
            bgWork.webquest(url, 'post', urlParam(data), '', function (sign, res) {
                if (!sign && res) {
                    if (res.code == 0) {
                        cb(null, {
                            token: res.token,
                            tzname: res.user_name,
                            host: host
                        })
                    } else cb(res.data)
                } else cb("团长网站出现问题")
            })
        } else dialog.msg('这并不是一个有效的域名')
    },
    tz_net_center: function tz_net_center(host, token, cb) {
        var url = "http://" + host + "/admin/user/center";
        bgWork.webquest(url, 'get', '', token, function (sign, res) {
            !sign && res ? cb(null, res) : cb("团长网站出现问题")
        })
    },
    tz_net_contraill: function tz_net_contraill(host, token) {
        var url = "http://" + host + "/admin/pluginunit/trail";
        var data = {
            goods_id: libCollect.getItemId(),
            goods_url: window.location.href,
            goods_img: $(".ks-imagezoom-wrap,.tb-booth").find("img")[0].src,
            goods_price: businessWork.getPrice(),
            goods_title: document.title.split('-')[0]
        };
        bgWork.webquest(url, 'post', urlParam(data), token, function (sign, res) { })
    },
    tz_net_status: function tz_net_status(host, token, cb) {
        var url = "http://" + host + "/admin/pluginunit/serchstatus";
        var data = {
            goods_id: libCollect.getItemId(),
            seller_id: libCollect.getSellerId()
        };
        bgWork.webquest(url, 'get', urlParam(data), token, function (sign, res) {
            !sign && res ? cb(null, res) : cb("团长网站出现问题")
        })
    },
    page: function page() {
        document.addEventListener("visibilitychange", function () {
            if (document.visibilityState == "hidden") {
                clearInterval(tzTimer)
            } else if (document.visibilityState == "visible") {
                clearInterval(tzTimer);
                tzTimer = setInterval(function () {
                    businessWork.timerhandle()
                }, 6000)
            }
        })
    },
    timerhandle: function timerhandle() {
        if ($_userinfo.lt_type == 0 && !isEmpty($_userinfo.lt_token) && !isEmpty($_userinfo.lt_host)) {
            businessWork.tz_step()
        }
    },
    getPrice: function getPrice() {
        var price = window.location.href.indexOf("item.taobao.com") > 0 ? $(".tb-rmb-num:last").text() : $(".tm-price:last").text();
        return price.indexOf("-") > 0 ? parseFloat(price.split("-")[0]) : parseFloat(price)
    },
    lt_perpare: function lt_perpare() {
        var $this = businessWork;
        $(".ltloginbox").html($this.html5);
        if (!isEmpty($_userinfo.lt_uid) && !isEmpty($_userinfo.lt_pwd)) {
            $("#ltName").val($_userinfo.lt_uid);
            $("#ltuserPwd").val($_userinfo.lt_pwd)
        }
    },
    lt_step: function lt_step() {
        var $this = businessWork,
            info = $_userinfo;
        var nTime = new Date().valueOf() - info.lt_stamp;
        if (Math.floor(nTime / 86400000) <= 7) {
            $(".ltuserbar").html($this.html6);
            let str = '<span style="margin-left:8px;">欢迎您,' + info.lt_zs_user + '</span>'
            //console.log('------', str)
            $(".ltmd").append(str);
            $(".ltuserwork").html($this.html2);
            IsLogin = true
        } else {
            $this.lt_loginout()
        }
    },
    lt_loginout: function lt_loginout() {
        var $this = businessWork;
        $_userinfo.lt_stamp = 0;
        localStorage.removeItem('itlogined')
        sessionStorage.removeItem('itlogined');
        libCollect.delcookie('itlogined');
        bgWork.setSettings('userInfo', JSON.stringify($_userinfo));
        $this.action();
        IsLogin = false
    },
    lt_net_login: function lt_net_login(uid, pwd, cb) {
        var url = 'http://zsxt.letuilm.com/api/newplug/login',
            // data = {
            //     password: pwd,
            //     remember: 1,
            //     source: "",
            //     username: uid
            // };
            data = {
                user: uid,
                pass: pwd,
            };
        // console.log('登录data', data)
        bgWork.post(url, data, 'json', function (s, n) {
            // console.log('登录返回', s, n)
            if (!s && n) {
                if (n.zs_token) {
                    IsLogin = true
                    cb('登录成功!', n)
                } else cb('登录失败!')
            } else cb('出现错误！')
        })
    },
    netui: function netui(un, cb) {
        var url = 'http://cai-api.yiquntui.com/index/index/getLimit?user=' + un;
        bgWork.get(url, 'json', function (sign, res) {
            if (!sign && res && res.code == 0) {
                var dt = res.result;
                if (!isEmpty(dt)) {
                    var day1 = new Date().valueOf(),
                        day2 = parseInt(dt.dateline) * 1000;
                    day1 <= day2 ? cb(null, parseInt(dt.limits)) : cb('错误')
                } else cb('错误')
            }
        })
    }
};
var markPages = {
    markXdw: function markXdw() {
        var $this = markPages,
            items = $("div.list-cell");
        $this.getTkyauthens(function (list) {
            $.map(items, function (item) {
                var goodid = $(item).children("i").attr("data-tid");
                list && list.map(function (_item) {
                    if (goodid == _item.itemid) {
                        var txt = "<div class=\"renzhengdan\"><span>" + _item.name + "</span></div>";
                        $(item).append(txt)
                    }
                });
                planWork.getCollectDirectRate(goodid, function (sign, res) {
                    if (!sign && res) {
                        var rate = parseFloat(res) / 100;
                        var txt = "<span class=\"dx_box\"><span class=\"dx_sp dx_tag\">定向&nbsp;&nbsp;" + rate + "%</span></span>";
                        $(item).append(txt)
                    }
                })
            })
        })
    },
    markDtk: function markDtk() {
        var $this = markPages,
            items = $("div.goods-item"),
            items2 = $("div.goods-yj");
        $this.getTkyauthens(function (list) {
            $.map(items, function (item) {
                var goodid = $(item).attr("data_goodsid");
                if (!goodid) {
                    var idss = $(item).id;
                    goodid = idss.split('_')[1]
                }
                var element = $(item).children("div.goods-item-content").children("div.goods-info").children("div.goods-qjy").children("div.goods-yj");
                var pr = $(element).children("p").text();
                var rate = parseFloat(pr.replace("%", ""));
                list && list.map(function (_item) {
                    if (goodid == _item.itemid) {
                        var txt = "<div class=\"renzhengdan\" id=\"gid-" + goodid + "\"><span>" + _item.name + "</span></div>";
                        $(item).append(txt)
                    }
                });
                planWork.getCollectDirectRate(goodid, function (sign, res) {
                    if (!sign && res) {
                        var $rate = parseFloat(res) / 100;
                        if ($rate > rate) {
                            var txt = "<div class=\"dx_brand\"><ul><li><div class=\"ifshow\">定向</div></li><li><div class=\"rg\">" + $rate + "%</div></li></ul></div>";
                            $(element).append(txt)
                        }
                    }
                })
            })
        })
    },
    getTkyauthen: function getTkyauthen(index, cb) {
        var url = "http://www.tkeasy.com/renzhengdan/" + (index == 1 ? '' : index);
        bgWork.get(url, "", function (sign, res) {
            if (sign) {
                var parser = new DOMParser();
                var htmldoc = parser.parseFromString(sign.responseText, "text/html");
                var elms = htmldoc.getElementsByClassName("subtitle"),
                    elms2 = htmldoc.getElementsByClassName("renzhengdan"),
                    renzhen = [],
                    nextflag = true;
                for (var n = 0; n < elms.length; n++) {
                    var gname = elms2[n].innerText.trim();
                    var str = elms[n].innerHTML;
                    str = str.trim();
                    str = str.replace(/\r\n/g, "");
                    str = str.replace(/(^\s+)|(\s+$)/g, "");
                    var day = /(\d+-\d+)/g.exec(str)[0],
                        gid = /btn_showsellcount.+data-id=.(\d+)./g.exec(str)[1];
                    today = new Date().format("MM-dd"), yesterday = new Date(new Date() - 24 * 60 * 60 * 1000).format("MM-dd");
                    if (day == yesterday) {
                        nextflag = false;
                        break
                    } else renzhen.push({
                        name: gname,
                        itemid: gid
                    })
                }
                cb(null, {
                    next: nextflag,
                    list: renzhen
                })
            } else cb('error')
        })
    },
    getTkyauthens: function getTkyauthens(pgk) {
        var $this = markPages,
            page = 1,
            next = true,
            list = [];
        ! function fn(page, next, list) {
            $this.getTkyauthen(page++, function (sign, res) {
                if (!sign && res) {
                    next = res.next, list = list.concat(res.list);
                    next ? fn(page, next, list, pgk) : pgk(list)
                } else pgk(list)
            })
        }(page, next, list, pgk)
    }
};
var checkStock = {
    action: function action() {
        var $this = checkStock;
        $this.getAreaIds()
    },
    getAreaIds: function getAreaIds() {
        var $this = checkStock;
        var url = 'https://division-data.alicdn.com/simple/addr_3_001.js?t=' + new Date().valueOf();
        bgWork.get(url, "", function (res) {
            if (res && res.responseText) {
                eval(res.responseText);
                if (tdist && tdist != null) {
                    var ids = Object.keys(tdist),
                        index = 0,
                        glist = [];
                    ! function fn(index, ids, pgk) {
                        var len = ids.length;
                        index < len ? (glist.push(index), checkStock.getStockNum(ids[index++]), fn(index, ids)) : pgk(glist)
                    }(index, ids, pgk)
                }
            }
        })
    },
    getStockNum: function getStockNum(areaid) {
        var url = 'https://mdskip.taobao.com/core/changeLocation.htm?',
            param = {
                queryDelivery: true,
                queryProm: true,
                tmallBuySupport: true,
                ref: encodeURIComponent(window.location.href),
                areaId: areaid,
                _ksTS: new Date().valueOf() + "_4580",
                callback: 'jsonp4581',
                isUseInventoryCenter: true,
                cartEnable: true,
                sellerUserTag3: 216806109434904736,
                service3C: false,
                sellerUserTag2: 1170937140066910216,
                isSecKill: false,
                isAreaSell: true,
                sellerUserTag4: 35596691079619,
                offlineShop: false,
                itemId: libCollect.getItemId(),
                sellerUserTag: 39391266,
                showShopProm: false,
                tgTag: false,
                isPurchaseMallPage: false,
                isRegionLevel: true,
                household: false,
                notAllowOriginPrice: false,
                addressLevel: 3
            };
        bgWork.get(url + urlParam(param), '', function (sign, res) {
            console.log(sign.responseText)
        })
    }
};
// 点击事件处理
var bindWork = {
    action: function action() {
        bindWork.bindBtnEvent();
        bindWork.bindAEvent();
        bindWork.bindIEvent();
        bindWork.bindSpanEvent();
        bindWork.bindInputEvent();
        bindWork.bindDivEvent();
        bindWork.bindTdEvent()
    },
    bindBtnEvent: function bindBtnEvent() {
        var $this2 = bindWork
        $(document).on("click", "button", function () {
            // console.log('点击btn', this)
            var _this2 = this;
            switch (this.id) {
                case 'login_tz':
                    var e = $("#txtDom").val(),
                        u = $("#ltName").val(),
                        p = $("#ltuserPwd").val(),
                        $this = businessWork;
                    e = e.replace("http://", "").replace("https://", "");
                    var d = e.split('/')[0];
                    $this.tz_net_login(d, u, p, function (n, m) {
                        if (!n && m) {
                            var info = {
                                lt_type: 0,
                                lt_dom: d,
                                lt_host: m.host,
                                lt_token: m.token,
                                lt_stamp: 0,
                                lt_uid: u,
                                lt_pwd: p,
                                lt_tzname: m.tzname
                            };
                            $_userinfo = info;
                            bgWork.setSettings("userInfo", JSON.stringify(info));
                            $this.action()
                        }
                        dialog.msg(!n && m ? '已经成功登陆！' : n)
                    });
                    break;
                case 'login_lt':
                    var u = $("#ltName").val(),
                        p = $("#ltuserPwd").val(),
                        $this = businessWork;
                    $this.lt_net_login(u, p, function (s, n) {
                        // console.log('登录之后', s, n)
                        if (s == '登录成功!') {
                            IsLogin = true
                            localStorage.setItem('itlogined', 'true');
                            sessionStorage.setItem('itlogined', 'true');
                            libCollect.writeCookie('itlogined', 'true', 24);
                            var info = {
                                lt_type: 1,
                                lt_dom: '',
                                lt_host: '',
                                lt_token: n.zs_token,
                                lt_stamp: new Date().valueOf(),
                                lt_uid: u,
                                lt_pwd: p,
                                lt_tzname: n.zs_user,
                                lt_zs_braId: n.zs_braId,
                                lt_zs_system: n.zs_system,
                                lt_zs_token: n.zs_token,
                                lt_zs_user: n.zs_user,
                                lt_zs_user_id: n.zs_user_id,
                            };
                            $_userinfo = info;
                            // console.log('$_userinfo', $_userinfo)
                            bgWork.setSettings("userInfo", JSON.stringify(info));
                            IsLogin = true
                            $this.action()
                        }
                        dialog.msg(!s && n ? '已经成功登陆！' : s)
                    });
                    break;
                case 'regist_lt':
                    window.open('http://www.shihuizhu.com/register', '_blank');
                    break;
                case 'contWW':
                    $this2.monitor()
                    var sign = $("#data-zd1").hasClass("sip-1") || $("#data-zd1").hasClass("sip-2");
                    if (IsLogin) {
                        if (sign) dialog.msg('你不能参与该商品的洽谈');
                        else {
                            var wangwang = window.location.host == "item.taobao.com" ? $(".ww-inline").attr("href") : "https://amos.alicdn.com/getcid.aw?v=3&groupid=0&s=1&charset=utf-8&uid=" + encodeURIComponent($(".slogo-shopname").children("strong")[0].innerText) + "&site=cntaobao";
                            window.open(wangwang, '_blank')
                        }
                    } else dialog.msg('登陆账号后才能使用功能！');
                    break;
                case "contDZ":
                    $this2.monitor()
                    var sign = $("#data-zd1").hasClass("sip-1") || $("#data-zd1").hasClass("sip-2");
                    if (IsLogin) {
                        if (sign) dialog.msg('你不能参与该商品的洽谈');
                        else window.open(contentWork.wangwangUrl(0), '_blank')
                    } else dialog.msg('登陆账号后才能使用功能！');
                    break;
                case "contYY":
                    $this2.monitor()
                    var sign = $("#data-zd1").hasClass("sip-1") || $("#data-zd1").hasClass("sip-2");
                    if (IsLogin) {
                        if (sign) dialog.msg('你不能参与该商品的洽谈');
                        else window.open(contentWork.wangwangUrl(1), '_blank')
                    } else dialog.msg('登陆账号后才能使用功能！');
                    break;
                case 'list_btn':
                    var sid = libCollect.getSellerId(),
                        date1 = new Date(new Date().format("yyyy-MM-dd")).getTime(),
                        limit = $_userinfo.lt_type == 0 ? 100 : 10,
                        allowSign = false;
                    businessWork.netui($_userinfo.lt_type == 0 ? $_userinfo.lt_tzname : $_userinfo.lt_uid, function (sign, litnum) {
                        limit = !sign && litnum ? litnum : limit;
                        bgWork.getSettings("userhanhan", function (objstr) {
                            if (!isEmpty(objstr)) {
                                var obj = JSON.parse(objstr);
                                var date2 = isNaN(obj.date) ? 0 : obj.date;
                                if (date1 == date2) {
                                    var index = obj.ids.findIndex(function ($id) {
                                        return $id == sid
                                    });
                                    if (index > -1) {
                                        allowSign = true
                                    } else if (index == -1 && obj.ids.length <= limit) {
                                        allowSign = true;
                                        obj.ids.push(sid)
                                    }
                                } else {
                                    obj.date = date1;
                                    obj.ids.length = 0;
                                    obj.ids.push(sid);
                                    allowSign = true
                                }
                                bgWork.setSettings("userhanhan", JSON.stringify(obj))
                            } else {
                                var data = {
                                    date: date1,
                                    ids: []
                                };
                                data.ids.push(sid);
                                allowSign = true;
                                bgWork.setSettings("userhanhan", JSON.stringify(data))
                            }
                            var talkSign = $("#data-zd1").hasClass("sip-1") || $("#data-zd1").hasClass("sip-2");
                            if (talkSign) dialog.msg('你不能参与该商品的洽谈');
                            else if (!IsLogin) dialog.msg('登陆账号后才能使用功能！');
                            else if (allowSign && IsLogin) contentWork.showBox();
                        })
                    });
                    break;
            }
            switch (this.className) {
                case 'special':
                    this.innerText = "已申请";
                    this.className = "special pass";
                    var ids = this.value.split("-"),
                        txt = $("input.reason").val();
                    bgWork.getToken(function (flag, token) {
                        if (!flag && token) {
                            planWork.applyPlan(ids[0], ids[1], txt == '' ? '申请通过。' : txt, token, function (sign, res) {
                                if (!sign && res) {
                                    setTimeout("getPlan.resetTable()", 500)
                                } else {
                                    _this2.innerText = "申请计划";
                                    _this2.className = "special";
                                    dialog.msg('你还没登陆阿里妈妈，登陆后再申请')
                                }
                            })
                        }
                    });
                    break;
                case 'special pass':
                    this.innerText = "申请计划";
                    this.className = "special";
                    var ids = this.value.split("-");
                    bgWork.getToken(function (flag, token) {
                        if (!flag && token) {
                            planWork.exitPlan(ids[2], token, function (sign, res) {
                                setTimeout("getPlan.resetTable()", 500)
                            })
                        }
                    });
                    break;
                case 'trans':
                    var turl = (window.location.host.indexOf("jd.com") > 0 ? "https://union.jd.com/proManager/index?pageNo=1&keywords=" : "https://pub.alimama.com/promo/search/index.htm?fn=search&q=") + encodeURIComponent(window.location.href);
                    window.open(turl, '_blank');
                    break;
                case 'effic':
                    var gid = libCollect.getItemId();
                    var url = 'http://open-api.shihuizhu.com/linkChange/checkGoods?gid=' + gid;
                    bgWork.get(url, 'json', function (s, n) {
                        !s && n ? n === 1 ? window.open('http://www.shihuizhu.com/details?id=' + gid, '_blank') : dialog.msg('暂时乐推没有收录该商品') : dialog.msg('该商品推广已失效')
                    });
                    break;
                case 'shape contact':
                case 'shape contact long':
                    if ($_userinfo.lt_type == 0 && !isEmpty($_userinfo.lt_token) && !isEmpty($_userinfo.lt_host)) {
                        businessWork.tz_net_contraill($_userinfo.lt_host, $_userinfo.lt_token)
                    }
                    break;
                case 'shopcoup':
                    var turl = 'https://login.taobao.com/member/login.jhtml';
                    window.open(turl, '_blank');
                    break
            }
        })
    },
    bindAEvent: function bindAEvent() {
        var $this = bindWork
        $(document).on("click", "a", function () {
            // console.log('点击a',$(this).first().children().text())
            if ($(this).first().children().text() == '旺旺在线') {
                $this.monitor()
            }
            switch (this.className) {
                case "jplanwork":
                    var idss = this.id;
                    if (idss.indexOf("jdpid") != -1) {
                        var ids = idss.split("-");
                        var pid = ids[1];
                        var turl = pid == 0 ? "https://union.jd.com/proManager/index?pageNo=1&keywords=" + encodeURIComponent(window.location.href) : "https://union.jd.com/proManager/planDetails?planId=" + pid;
                        window.open(turl, '_blank')
                    }
                    break;
                case "planwork":
                    var idss = this.id;
                    if (idss.indexOf("cuid") != -1) {
                        var ids = idss.split("-");
                        var cid = parseInt(ids[1]),
                            uid = parseInt(ids[2]),
                            sid = libCollect.getSellerId();
                        var turl = "http://pub.alimama.com/myunion.htm?#!/promo/self/campaign?campaignId=" + cid + "&shopkeeperId=" + uid + "&userNumberId=" + sid;
                        if (cid == 1 && uid == 0) {
                            turl = "http://pub.alimama.com/promo/item/channel/index.htm?q=" + encodeURIComponent(window.location) + "&channel=qqhd"
                        }
                        if (cid == 0 && uid == 0) {
                            turl = "http://pub.alimama.com/promo/search/index.htm?fn=search&q=" + encodeURIComponent(window.location)
                        }
                        window.open(turl, '_blank')
                    }
                    break;
                case "couponwork":
                    var idss = this.id;
                    if (idss.indexOf("aid") != -1) {
                        var ids = idss.split("-");
                        var aid = ids[1],
                            type = parseInt(ids[2]),
                            sid = libCollect.getSellerId();
                        switch (type) {
                            case 0:
                                var turl = "https://market.m.taobao.com/apps/aliyx/coupon/detail.html?wh_weex=true&seller_id=" + sid + "&activity_id=" + aid;
                                libCollect.openWin(turl);
                                break;
                            case 1:
                                var turl = "https://uland.taobao.com/quan/detail?sellerId=" + sid + "&activityId=" + aid;
                                libCollect.openWin(turl);
                                break;
                            case 3:
                                var turl = "http://pub.alimama.com/promo/search/index.htm?fn=search&q=" + encodeURIComponent(window.location);
                                window.open(turl, '_blank');
                                break
                        }
                    }
                    break;
                case "loginwarring":
                    var turl = window.location.host.indexOf("jd.com") > 0 ? 'https://union.jd.com/index' : 'http://pub.alimama.com';
                    window.open(turl, '_blank');
                    break
            }
        })
    },
    bindIEvent: function bindIEvent() {
        $(document).on("click", "i", function () {
            // console.log('点击i', this)
            var $id = this.id;
            if ($id == "docW") tkDocWork.showBox();
            else if ($id == "tkyW") platformWork.trendBox(), spreadformWork.trendBox();
            else if ($id == "excellW") window.open('http://www.shihuizhu.com/goodsDetail/' + libCollect.getItemId(), '_blank')
        })
    },
    bindSpanEvent: function bindSpanEvent() {
        $(document).on("click", "span", function () {
            // console.log('点击span', this)
            switch (this.id) {
                case 'login-out':
                    var $this = businessWork,
                        $info = $_userinfo;
                    if ($info.lt_type == 0) {
                        $this.tz_loginout()
                    } else if ($info.lt_type == 1) {
                        $this.lt_loginout()
                    }
                    break
            }
        })
    },
    bindInputEvent: function bindInputEvent() {
        $(document).on("input propertychange", "input:text", function () {
            if (this.className == "reason") {
                var res = $(this).val();
                bgWork.setSettings('reason', res ? res : '请允许通过计划。')
            }
        });
        $(document).on("click", "input:checkbox", function () {
            if (this.id == "unfoldST") {
                var url = 'https://shihuizhu3920-1302253966.cos.ap-nanjing.myqcloud.com/tbPropImg.css';
                if (this.hasAttribute("checked")) {
                    var nodes = document.getElementsByTagName("link");
                    for (var i = 0; i < nodes.length; i++) {
                        if (nodes[i] && nodes[i].getAttribute("href") != null && nodes[i].getAttribute("href") == url) {
                            nodes[i].parentNode.removeChild(nodes[i]);
                            break
                        }
                    }
                    $(this).removeAttr("checked")
                } else {
                    var node = document.createElement("link");
                    node.setAttribute('href', url);
                    node.setAttribute('type', 'text/css');
                    node.setAttribute('charset', 'utf-8');
                    node.setAttribute('rel', 'stylesheet');
                    document.getElementsByTagName('head')[0].appendChild(node);
                    $(this).attr("checked", "")
                }
            }
        })
    },
    bindDivEvent: function bindDivEvent() {
        $(document).on("click", "div", function () {
            // console.log('点击div', this)
            switch (this.className) {
                case 'bubble':
                    window.open('http://www.shihuizhu.com/center/commander', '_blank');
                    break;
                case "login-btn":
                    $(".ltuserwork").html(businessWork.html3);
                    break;
                case "tong close":
                    $(".LTplugin").remove();
                    $(".LSKUskin").remove();
                    $(".LTcontact").remove();
                    break;
                case "renzhengdan":
                    var idss = this.id.split('-');
                    if (idss.length == 2) {
                        dialog.iframe({
                            title: '销量与传播记录',
                            width: '600px',
                            length: '90%',
                            url: "https://www.tkeasy.com/item/" + idss[1]
                        })
                    }
                    break
            }
        })
    },
    bindTdEvent: function bindTdEvent() {
        $(document).on("mouseenter", "td#coupname", function () {
            $(this).children("div.tip").attr("style", "display:block;")
        });
        $(document).on("mouseleave", "td#coupname", function () {
            $(this).children("div.tip").attr("style", "display:none;")
        })
    },
    //监控联系商家callback
    monitor: function monitor() {
        let url = 'https://zsxt.letuilm.com/api/v1/wwLog'
        let data = {
            nick: libCollect.getShopName(),
            title: libCollect.getGoodsName(),
            itemId: libCollect.getItemId(),
            sellerId: libCollect.getShopId(),
            user: $_userinfo.lt_zs_user
        }
        // console.log('点击返回',data)
        $.post(url, data, function (res, msg) {
            // console.log('点击上传返回',res,err)
            // console.log('呀吼')
            return res
        })
    }
};
var pageWork = {
    action2: function action2() {
        pageWork.modElement();
    },
    action: function action() {
        pageWork.perpare();
        pageWork.modElement();
        pageWork.chipboad()
    },
    perpare: function perpare() {
        bgWork.getVersion(function (v) {
            // var db = "<div class=\"tbk-addin pluginclear\"><div class=\"tbk-addin-wv\">\n                        <p>当前版本：v" + v + "</p>\n                        <p><a href=\"http://www.shihuizhu.com\" target=\"_blank\">http://www.shihuizhu.com</a></p>\n                    </div>\n                    <div class=\"tbk-addin-qr\">\n                        <p>点击链接加入群聊：<br>\n                            <a href=\"https://jq.qq.com/?_wv=1027&k=fnfCqWzo\">乐推官方交流QQ群:320490934\n                        </p>\n                        <img src=\"https://shihuizhu3920-1302253966.cos.ap-nanjing.myqcloud.com/qrimg.png\" width=\"75\" height=\"75\">\n                    </div>";
            var db = ''
            for (var i = 1; i <= 6; i++) {
                $("#panel-" + i).after(db)
            }
        });
        bgWork.getSettings("reason", function (reason) {
            $("input.reason").val(reason ? reason : "请允许通过计划。")
        });
        $("#noname").attr("style", "display:none;");
        setTimeout(function () {
            pageWork.autoFloot()
        }, 1500);
        setTimeout(function () {
            couponWork && couponWork.nums == 0 && $("#couponheader").append('<tr><td colspan="6" class="center"><a class="">此商品并无优惠劵</a></td></tr>')
        }, 2500);
        $(".tb-skin").length > 0 && $(".tb-skin").children(":first").before("<div class=\"LSKUskin\">\n            <label class=\"switch\" title=\"展开SKU文字\">\n            <input id=\"unfoldST\" type=\"checkbox\" >\n            <div class=\"slider\"></div><span class=\"skutext\">展开SKU文字</span>\n        </label></div>")
    },
    modElement: function modElement() {
        $(".lt_column").mouseenter(function () {
            var baname = $(this).children("div.title").text();
            if (baname == "榜单" && $(".ltrank2").children().length < 1) {
                platformWork.showRanks()
                spreadformWork.showRanks()
            }
            $.each($(".lt_column"), function (i, item) {
                $(item).removeClass("open");
                $(item).children(".panel").removeClass("show")
            });
            $(this).addClass("open");
            $(this).children(".panel").addClass("show");
            $(".ltcontent").css("margin-bottom", $(".show").innerHeight() + 10);
            pageWork.autoFloot()
        });
        $(".ltcontent").mouseleave(function () {
            $.each($(".lt_column"), function (i, item) {
                $(item).removeClass("open");
                $(item).children(".panel").removeClass("show")
            });
            $(".ltcontent").css("margin-bottom", 5)
        })
    },
    autoFloot: function autoFloot() {
        var items = $("div.show").children(),
            Y = 0,
            i = 0;
        $.map(items, function (item) {
            if (i++ < items.length - 1) Y += $(item).innerHeight()
        });
        Y > 205 ? $("div.show").children(".tbk-addin").removeClass("pluginclear") : $("div.show").children(".tbk-addin").addClass("pluginclear")
    },
    chipboad: function chipboad() {
        var copyUrl = new ClipboardJS('.couponurl');
        copyUrl.on('success', function (e) {
            dialog.msg('复制成功')
        });
        copyUrl.on('error', function (e) {
            dialog.msg('复制失败')
        })
    }
};

var titleBar = {
    action: function action() {
        var $this = titleBar;
        $this.getBar();
        $this.getCount();
        $this.changebar()
        $this.creatdom()
        // $this.getLine()
        $this.changedata()
        $('.databaractive').trigger("click");
    },
    //顶部  分类获取数据
    getBar: function getBar() {
        var $this = titleBar;
        //聚划算info
        var url = 'https://dskip.ju.taobao.com/detail/json/item_dynamic.htm?item_id=' + libCollect.getItemId();
        // var url = 'https://dskip.ju.taobao.com/detail/json/item_dynamic.htm?item_id=607093302330';
        bgWork.get(url, "json", function (err, res) {
            // console.log('聚划算返回', err, res)
            if (res.data.soldCount && res.data.stock) {
                let zh = (res.data.soldCount / (Number(res.data.soldCount) + Number(res.data.stock)) * 100).toFixed(2);
                let sold = `<em class="emt">` + res.data.soldCount + `</em>`
                let zhc = `<em class="emt">` + zh + `</em>` + `%`
                $('.jhsxl').append(sold)
                $('.gql').append(zhc)
            } else {
                if (res.data.itemSoldDesc) {
                    $('.LT-TitlerTwo').find('.jhsinfo').html(res.data.itemSoldDesc)
                } else if (res.data.remindNum) {
                    let srt = `<em class="num">` + res.data.itemSoldDesc + `</em>人想买`
                    $('.LT-TitlerTwo').find('.jhsinfo').html(srt)
                } else {
                    $('.LT-TitlerTwo').find('.jhsinfo').text('Sorry,该商品没有参加聚划算哦!')
                }
            }
            // console.log(zh)
        })
        //私域 产品 上单 info
        let infourl = 'https://zsxt.letuilm.com/api/Newplug/checkGoods'
        let data = {
            itemId: libCollect.getItemId(),
            sellerId: libCollect.getShopId()
        }
        bgWork.post(infourl, data, "json", function (err, res) {
            // console.log('顶部info', err, res)
            let zanwu = `<em class="emt">暂无</em>`
            let state = `<em class="emt">` + res.state + `</em>`
            $('.LT-TitlerThree').find('.isonline').html(state)

            if (res.wwNum) { //沟通次数
                let wwNum = `<em class="emt">` + res.wwNum + `</em>`
                $('.LT-TitlerFour').find('.gtcs').append(wwNum)
            } else {
                $('.LT-TitlerFour').find('.gtcs').append(zanwu)
            }
            if (res.wwTime) { //最后沟通时间
                let wwTime = `<em class="emt">` + res.wwTime + `</em>`
                $('.LT-TitlerFour').find('.zhgtsj').append(wwTime)
            } else {
                $('.LT-TitlerFour').find('.zhgtsj').append(zanwu)
            }

            let pushGoodsState = `<em class="emt">` + res.pushGoodsState + `</em>`
            $('.LT-TitlerFive').find('.ksd').append(pushGoodsState)
            if (res.pushComm) { //上期佣金
                let pushComm = `<em class="emt">` + res.pushComm + `</em>`
                $('.LT-TitlerFive').find('.sqyj').append(pushComm)
            } else {
                $('.LT-TitlerFive').find('.sqyj').append(zanwu)
            }
            if (res.pushPrice) { //上期卷后价
                let pushPrice = `<em class="emt">` + res.pushPrice + `</em>`
                $('.LT-TitlerFive').find('.sqjhj').append(pushPrice)
            } else {
                $('.LT-TitlerFive').find('.sqjhj').append(zanwu)
            }
        })
    },
    //关键字 类型数量
    getCount: function getCount() {
        var $this = titleBar;
        //   var base = {"iids": [libCollect.getItemId()]};
        // https://ext.dianchacha.com/ext/2.0/keyword/count/?ver=2.4.5&id=bndfplpgdhpmlhmbajjnebihjfmcdmme&key=20191001&data=%7B%22iids%22%3A%5B%22620195499445%22%5D%7D&sign=6a3154be9fe0adb78429b2b08785ae53&t=1599182319024&uuid=62d7ddc7-5f3c-4c95-b82f-47fff192a0bc
        var url = 'https://ext.dianchacha.com/ext/2.0/keyword/count/??ver=2.4.5&id=bndfplpgdhpmlhmbajjnebihjfmcdmme&key=20191001&data=' +
            '%7B%22iids%22%3A%5B%22' + libCollect.getItemId() + '%22%5D%7D' + '&sign=6a3154be9fe0adb78429b2b08785ae53&t=' +
            new Date().valueOf() + '&uuid=62d7ddc7-5f3c-4c95-b82f-47fff192a0bc';
        // var url = 'https://ext.dianchacha.com/ext/2.0/keyword/count/'
        //   let data = {
        //     ver: '2.4.5',
        //     id: 'bndfplpgdhpmlhmbajjnebihjfmcdmme',
        //     key: 20191001,
        //     data:'%7B%22iids%22%3A%5B%22'+libCollect.getItemId()+'%22%5D%7D',  
        //     // { "iids": [libCollect.getItemId()],},
        //     sign: '6a3154be9fe0adb78429b2b08785ae53',
        //     t: Math.round(new Date().getTime()/1000),
        //     uuid: '62d7ddc7-5f3c-4c95-b82f-47fff192a0bc',
        // };
        // console.log('加密','%7B%22iids%22%3A%5B%22620195499445%22%5D%7D')
        // console.log('解密','{"iids":["620195499445"]}')
        console.log('url', url)
        $.get(url, function (res, err) {
            // console.log('返回',res,err)
            $('.tbpc').find('.em_red').text(res.result[libCollect.getItemId()].tb)
            $('.tbpcztc').find('.em_red').text(res.result[libCollect.getItemId()].p4p_tb)
            $('.wx').find('.em_red').text(res.result[libCollect.getItemId()].h5)
            $('.wxztc').find('.em_red').text(res.result[libCollect.getItemId()].p4p_h5)
        })
    },
    //获取关键字里时间事件
    getLine: function getLine(type, temp, cb) {
        var $this = titleBar;
        var url = 'https://ext.dianchacha.com/ext/2.0/keyword/itemday';
        // var type = 'tb';
        // var temp = 1598889600;
        // console.log(type)
        let data = {
            ver: '2.4.2',
            id: 'ckfdjapnpbkafkkbimifjeohlemamoal',
            key: 20191001,
            data: JSON.stringify({
                "iid": libCollect.getItemId(),
                "p": type,
                "t": temp
            }),
            sign: '9caabffc1a219195ca5e14b8eced9097',
            t: new Date().valueOf(),
            uuid: 'c97f898b-f824-4314-9ffa-df8fa29d05e9',
        };

        // console.log('data', data)
        bgWork.post(url, data, "json", function (err, res) {
            // console.log('关键词返回', err, res)
            cb(null, res)
        })
    },
    //关键字 类型hover事件
    changebar: function changebar() {
        $(".titlebar").mouseenter(function () {
            $.each($(".titlebar"), function (i, item) {
                $(item).removeClass("baractive");
                $(item).children(".panel").removeClass("show")
            });
            $(this).addClass("baractive");
            $(this).children(".poab").addClass("poabshow");
        });
        $(".titlebar").mouseleave(function () {
            $.each($(".titlebar"), function (i, item) {
                $(item).removeClass("baractive");
                $(item).children(".poab").removeClass("poabshow")
            });
        })
    },
    //获取时间
    getDate: function getDate(date, day) {
        var dd = new Date(date);
        dd.setDate(dd.getDate() + day);
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1 < 10 ? "0" + (dd.getMonth() + 1) : dd.getMonth() + 1;
        var d = dd.getDate() < 10 ? "0" + dd.getDate() : dd.getDate();
        return y + "-" + m + "-" + d;
    },
    //生成关键字类型dom
    creatdom: function creatdom() {
        var $this = titleBar;
        var dateline = `<div class="databox">`;
        for (let i = 0; i < 7; i++) {
            let da = $this.getDate(new Date(), -(i + 1))
            let danum = new Date(da).getTime(da) + ""
            $this.temp = danum.substring(0, danum.length - 3)
            dateline += `<div class="databar" data-num="` + danum.substring(0, danum.length - 3) + `" data-full="` + da + `">` + da.substring(da.length - 5, da.length) + `</div>`
            //    console.log($this.getDate(new Date(),-(i+1)))
        }
        dateline += `</div><div class="lt_rankbox"></div>`
        // console.log(dateline)
        // console.log($('.poab'))
        $('.poab').html(dateline)
        // console.log($(".databox"))
        $.each($('.databox'), function (i, item) {
            $(item).find(".databar").first().addClass("databaractive")
        });
    },
    //关键字类型里时间切换事件
    changedata: function changedata() {
        var $this = titleBar;
        $("div.databar").click(function () {
            // console.log('this',$(this).attr("data-num"))
            // console.log('this',$(this).parent().parent().parent().attr('data-type'))
            let temp = $(this).attr("data-num")
            let type = $(this).parent().parent().parent().attr('data-type')
            var parentdom = $(this).parent().parent()
            $this.getLine(type, temp, function (err, res) {
                // console.log('选择日期之后',err,res)
                // var list=res.result.data
                if (res.result.data.length > 0) {
                    var rankstr = ``
                    for (let i = 0; i < res.result.data.length; i++) {
                        // console.log(res.result.data[i])
                        rankstr += `<div class="rankinfo">
                        <div>` + res.result.data[i].keyword + `</div>
                        <div>第<em class="em_red">` + res.result.data[i].page + `</em>页， 第<em class="em_red">` + res.result.data[i].pos + `</em>位</div>
                        </div>`
                    }
                    // console.log('rankstr',rankstr)
                    // console.log($(parentdom))
                    $(parentdom).find('.lt_rankbox').html(rankstr)
                } else {
                    // cb('暂无信息')
                    var nonestr = `<div style="margin:15px auto;text-align:center;color:#333;">Sorry,暂无信息!</div>`
                    $(parentdom).find('.lt_rankbox').html(nonestr)
                    console.log('暂无信息')
                }
            })
            $.each($(this), function (i, item) {
                // console.log('item',$(item).parent())
                $(item).parent().find('.databar').removeClass("databaractive")
            });
            $(this).addClass("databaractive")
        });
    }
};
var logindom = {
    action: function action() {
        var $this = logindom;
        $this.getArt();
        setTimeout(() => {
            $this.sendCookie();
        }, 2000);
        // $this.bindLogin();
    },
    action2: function action2() {
        var $this = logindom;
        $this.sendCookie();
    },
    getArt: function getArt() {
        var $this = logindom;
        layer.open({
            type: 1,
            title: '乐推插件登录',
            closeBtn: 1,
            btn: ['&nbsp;登 &nbsp; 录&nbsp;'],
            btnAlign: 'c',
            maxmin: true,
            shadeClose: true,
            area: ['280px', '171px'],
            // skin: 'yourclass',
            zIndex: 999999990,
            content: `<div style="padding: 10px 10px 0px 10px;">
                        <div style="display:flex;justify-content: center;align-items:center;margin-bottom:8px;">
                            <span style="">用户账号:</span>
                            <input id=\"ltUserName\" type=\"text\" placeholder=\"请输入您的用户名\" style="height: 21px;padding: 3px 8px;border: 1px solid #eaeaea;border-radius: 4px;">\n         </br>\n     
                        </div>
                        <div style="display:flex;justify-content: center;align-items:center;">
                            <span style="">用户密码:</span>
                            <input id=\"ltUserPass\" type=\"password\" placeholder=\"请输入您的密码\" style="height: 21px;padding: 3px 8px;border: 1px solid #eaeaea;border-radius: 4px;">\n        </br>\n 
                        </div>
                            </div>`,
            yes: function (index, layero) {
                // console.log(index, layero)
                var u = $("#ltUserName").val(),
                    p = $("#ltUserPass").val(),
                    $this = logindom;
                $this.lt_login(u, p, function (s, n) {
                    // console.log('开局登录之后', s, n)
                    if (s == '登录成功!') {
                        IsLogin = true
                        var info = {
                            lt_type: 1,
                            lt_dom: '',
                            lt_host: '',
                            lt_token: n.zs_token,
                            lt_stamp: new Date().valueOf(),
                            lt_uid: u,
                            lt_pwd: p,
                            lt_tzname: n.zs_user,
                            lt_zs_braId: n.zs_braId,
                            lt_zs_system: n.zs_system,
                            lt_zs_token: n.zs_token,
                            lt_zs_user: n.zs_user,
                            lt_zs_user_id: n.zs_user_id,
                        };
                        $_userinfo = info;
                        // console.log('$_userinfo', $_userinfo)
                        localStorage.setItem('itlogined', 'true');
                        sessionStorage.setItem('itlogined', 'true');
                        libCollect.writeCookie('itlogined', 'true', 24);
                        bgWork.setSettings("userInfo", JSON.stringify(info));
                        $this.action()

                        businessWork.action();
                        webWork.showOut2(titleTB);
                        titleBar.action();
                        getPlan.action();
                        platformWork.action();
                        spreadformWork.action();
                        dealImg.action();
                        salesWork.action();
                        historyWork.action();
                        pageWork.action();
                        tkDocWork.action();
                        layer.closeAll()
                        IsLogin = true
                    }
                    dialog.msg(!s && n ? '已经成功登陆！' : s)
                });
            },
            // btn2: function (index, layero) {
            //     console.log('注册')
            // }
        });
    },
    lt_login: function lt_login(uid, pwd, cb) {
        var url = 'http://zsxt.letuilm.com/api/newplug/login',
            data = {
                user: uid,
                pass: pwd,
            };
        // console.log('登录data', data)
        if (uid !== "" && pwd !== "") {
            bgWork.post(url, data, 'json', function (s, n) {
                // console.log('登录返回', s, n)
                if (n) {
                    if (n.zs_token) {
                        IsLogin = true
                        cb('登录成功!', n)
                    } else {
                        dialog.msg(n.msg)
                    }
                } else cb('出现错误！')
            })
        } else {
            dialog.msg('请输入用户名和密码!')
        }
    },
    //上传cookie
    sendCookie: function sendCookie() {
        var $this = logindom;
        var username = libCollect.getUserName()
        // console.log('username',username)
        let url = "https://zsxt.letuilm.com/api/v2/setTbCook"
        if (username !== '') {
            var t = 'https://taobao.com/'
            bgWork.getCookies(t, function (e, r) {
                let arr = r.split("; ")
                // let str = getcoupon.getck(arr, '_m_h5_tk')
                let data = {
                    tbname: username,
                    cook: r
                }
                //  console.log('-----获取cookie',r)
                bgWork.post(url, data, 'json', function (res, err) {
                    //   console.log('cookie上传返回',res,err)
                })
            })
            // console.log('username', username)
        } else {
            console.log('暂未登录')
        }
    }
};
//领取优惠券
var getcoupon = {
    cou_id: '',//
    cou_url: '',//优惠卷地址
    sellerId: '',
    activityId: '',
    mh5tk: '',
    sign: '',
    t: '',
    action: function action() {
        var $this = getcoupon;
        $this.geturl();
    },
    geturl: function geturl() {
        var $this = getcoupon;
        let url = 'https://zsxt.letuilm.com/api/Newplug/getCouponUrl';
        bgWork.get(url, 'json', function (s, n) {
            // console.log('获取优惠卷地址返回', s, n)
            $this.cou_id = n.cou_id;
            $this.cou_url = n.cou_url;
            $this.sellerId = $this.geturlpar($this.cou_url, 'sellerId');
            $this.activityId = $this.geturlpar($this.cou_url, 'activityId');
            //    console.log('$this.sellerId',$this.sellerId)
            //    console.log('$this.activityId',$this.activityId)
            // cou_url: "https://uland.taobao.com/quan/detail?sellerId=2207983990397&activityId=9a873e128692400a87fc33537cb6f00f&coupon_number=0&coupon_total=1000"
            $this.dogetcoupon()
        })
    },
    geturlpar: function geturlpar(urlstr, name) { //获取url参数
        // console.log('urlstr', urlstr,'name',name);
        let i = urlstr.indexOf('?');
        urlstr = urlstr.slice(i, urlstr.length);// ?id=xxxxx&a=xxx
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)');
        var r = urlstr.substr(1).match(reg);
        if (r != null) {
            return unescape(r[2]);
        } else {
            return null;
        }
    },
    getck: function getck(acookie, sname) {//获取单个cookies
        for (var i = 0; i < acookie.length; i++) {
            var arr = acookie[i].split("=");
            if (sname == arr[0]) {
                if (arr.length > 1)
                    return unescape(arr[1]);
                else
                    return "";
            }
        }
        return "";
    },
    dogetcoupon: function dogetcoupon() {
        var $this = getcoupon;
        bgWork.getCookies('https://taobao.com/', function (e, r) {
            let arr = r.split("; ")
            let str = $this.getck(arr, '_m_h5_tk')
            $this.t = new Date().getTime();
            $this.mh5tk = str.slice(0, str.length - 14)
            let str2 = `{"sellerId":"` + $this.sellerId + `","activityId":"` + $this.activityId + `","pid":"mm_0_0_0","mteeUa":"","umidToken":"T2gAU9bDlb0YMRQavzxA6htNGmR_DaVW6I9jG1AMPsH9oPT-84KCqZzrhAr5FJrbG1z0371_PRkbA6FtGpOxwh2n"}`
            let str3 = $this.mh5tk + `&` + $this.t + `&12574478&` + str2;
            let str4 = encodeURIComponent(str2).replace(/_/g, '%5F');
            $this.sign = MD5(str3)
            let url = `https://acs.m.taobao.com/h5/mtop.alimama.union.hsf.mama.coupon.apply/1.0/?jsv=2.3.16&appKey=12574478&t=` + $this.t
                + `&sign=` + $this.sign + `&api=mtop.alimama.union.hsf.mama.coupon.apply&AntiCreep=true&v=1.0&ecode=1&LoginRequest=true&type=jsonp&dataType=jsonp&callback=mtopjsonp3&data=` + str4;
            bgWork.get(url, 'json', function (s, n) {
                let str = s.responseText;
                str = str.slice(12, str.length - 1)
                let res = JSON.parse(str)
                console.log('领取返回', res)
                if (res.data.result) {
                    if (res.data.result.retStatus == '0') {
                        $this.uploadsucc('succ')
                    }
                    if (res.data.result.msgInfo == 'COUPON_NOT_EXISTS' || res.data.result.retStatus == '5') {
                        $this.uploadsucc('del')
                    }
                } else {
                    // console.log('未登录')
                    window.clearInterval(timerc)
                }
            })
        })
    },
    uploadsucc: function uploadsucc(type2) {
        var $this = getcoupon;
        let url = 'https://zsxt.letuilm.com/api/Newplug/setCoupon',
            data = {
                cou_id: $this.cou_id,
                type: type2
            };
        bgWork.post(url, data, 'json', function (s, n) {
            // console.log('反馈返回', s,n)
        })
    }
};

if (webWork.isShow()) {
    switch (window.location.host) {
        case 'item.jd.com':
            webWork.showOut(outHtmlJD);
            jdPlan.doing();
            historyWork.action(1);
            pageWork.action();
            bindWork.action();
            break;
        default:
            webWork.showOut(outHtmlTB);
            window.clearInterval(timerc)
            var timerc = setInterval(() => {
                getcoupon.action()
            }, 10000)
            // console.log('cookielogined',libCollect.readCookie('itlogined'))
            if (localStorage.getItem('logined')) {
                localStorage.removeItem('logined')
            }
            if (!localStorage.getItem('itlogined') && !sessionStorage.getItem('itlogined') && !libCollect.readCookie('itlogined')) {
                logindom.action();
                bindWork.action();
            } else {
                businessWork.action();
                webWork.showOut2(titleTB);
                titleBar.action();
                getPlan.action();
                platformWork.action();
                spreadformWork.action();
                dealImg.action();
                salesWork.action();
                historyWork.action();
                pageWork.action();
                bindWork.action();
                tkDocWork.action();
                setTimeout(() => {
                    logindom.action2();
                }, 2000);
            }
            break
    }
}